C#中读写INI文件

  c#的类没有直接提供对ini文件的操作支持,可以自己包装win api的WritePrivateProfileString和GetPrivateProfileString函数实现。下面提供一个包装类,可以直接使用。

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks; namespace ESIMRobotSystem
{
class Robot_WriteAndReadInitCls
{
public string inipath;
/// <summary>
/// 申明INI文件的写操作函数
/// </summary>
/// <param name="section">INI文件中的段落</param>
/// <param name="key">INI文件中的关键字</param>
/// <param name="val">INI文件中关键字的数值</param>
/// <param name="filePath">INI文件的完整的路径和名称</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(
string section,
string key,
string val,
string filePath
); /// <summary>
/// 申明INI文件的读操作函数
/// </summary>
/// <param name="section">INI文件中的段落名称</param>
/// <param name="key">INI文件中的关键字</param>
/// <param name="def">无法读取时候时候的缺省数值</param>
/// <param name="retVal">读取数值</param>
/// <param name="size">数值的大小</param>
/// <param name="filePath">INI文件的完整路径和名称</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(
string section,
string key,
string def,
StringBuilder retVal,
int size,
string filePath
); /// <summary>
/// 构造方法
/// </summary>
/// <param name="INIPath">文件路径</param>
public Robot_WriteAndReadInitCls(string INIPath)
{
inipath = INIPath;
} /// <summary>
/// 写入INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
/// <param name="Value">值</param>
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.inipath);
} /// <summary>
/// 读出INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder();
int i = GetPrivateProfileString(Section, Key, "", temp, , this.inipath);
return temp.ToString();
} /// <summary>
/// 验证文件是否存在
/// </summary>
/// <returns>布尔值</returns>
public bool ExistINIFile()
{
return File.Exists(inipath);
}
}
}
04-15 14:13