C#- 操作Ini文件

时间:2023-03-10 01:58:17
C#- 操作Ini文件

  以前习惯了使用.NET中的WEB.CONFIG或者APP.CONFIG,最近在做项目的时候遇到了些问题,发现没办法使用这些CONFIG文件。一开始我的做法是建一个文本文件,自己定规律,自己写方法去写新的配置项和读配置项,虽然基本都能实现了,但做的很一般,不够简洁明了。然后我想过用XML来做配置文件,最后又发现INI文件。INI文件已经有别人写好的DLL可以用了,了解多了一些后看到很多软件也用这INI,包括我们的WINDOWS系统也用了很多INI文件,我用了下感觉很不错。

  在网上的了一些文章,再整理了一下下,记录如下,做一个备忘

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; namespace IniFileDemo
{
public class IniFile
{
public string Path; public IniFile(string path)
{
this.Path = path;
} #region 声明读写INI文件的API函数
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath); [DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
#endregion /// <summary>
/// 写INI文件
/// </summary>
/// <param name="section">段落</param>
/// <param name="key">键</param>
/// <param name="iValue">值</param>
public void IniWriteValue(string section, string key, string iValue)
{
WritePrivateProfileString(section, key, iValue, this.Path);
} /// <summary>
/// 读取INI文件
/// </summary>
/// <param name="section">段落</param>
/// <param name="key">键</param>
/// <returns>返回的键值</returns>
public string IniReadValue(string section, string key)
{
StringBuilder temp = new StringBuilder(); int i = GetPrivateProfileString(section, key, "", temp, , this.Path);
return temp.ToString();
} /// <summary>
/// 读取INI文件
/// </summary>
/// <param name="Section">段,格式[]</param>
/// <param name="Key">键</param>
/// <returns>返回byte类型的section组或键值组</returns>
public byte[] IniReadValues(string section, string key)
{
byte[] temp = new byte[]; int i = GetPrivateProfileString(section, key, "", temp, , this.Path);
return temp;
} }
}

读写DEMO

private void button1_Click(object sender, EventArgs e)
        {
            IniFile ini = new IniFile(@"d:\abc.ini");
           
            //读
            //byte[] sectionByte = ini.IniReadValues("Person", "Love");
            //string result = System.Text.Encoding.ASCII.GetString(sectionByte);
            //MessageBox.Show(result);

//写
            //ini.IniWriteValue("Person", "Love", "Girl");

}