C#对INI配置文件进行读写操作方法
#region 读写ini配置文件
/// <summary>
/// 对INI文件进行读写
/// </summary>
class INIHelper
{
/// <summary>
/// 从INI文件中读取数据
/// </summary>
/// <param name="filePath">INI文件的全路径</param>
/// <param name="rootValue">根节点值,例如根节点[URLConfig]的值为:URLConfig</param>
/// <param name="key">根节点下的键,例如url</param>
/// <param name="defValue">当标记值未设定或不存在时的默认值</param>
/// <returns></returns>
public static string ReadFromINI(string filePath, string rootValue, string key, string defValue = "")
{
StringBuilder sb = new StringBuilder(1024);
GetPrivateProfileString(rootValue, key, defValue, sb, 1024, filePath);
return sb.ToString();
}
/// <summary>
/// 对INI文件进行写入操作
/// </summary>
/// <param name="filePath">INI文件的全路径</param>
/// <param name="rootValue">根节点值,例如根节点[URLConfig]的值为:URLConfig</param>
/// <param name="key">根节点下的键,例如url</param>
/// <param name="newVal">想要修改的内容</param>
/// <returns></returns>
public static void WriteToINI(string filePath, string rootValue, string key, string newVal)
{
WritePrivateProfileString(rootValue, key, newVal, filePath);
}
/// <summary>
/// 对INI文件进行读取操作
/// </summary>
/// <param name="IpAppName">表示INI文件内部根节点的值</param>
/// <param name="IpKeyName">表示根节点下子标记的值</param>
/// <param name="IpDefault">表示当标记值未设定或不存在时的默认值</param>
/// <param name="IpReturnString">返回读取节点的值</param>
/// <param name="nSize">读取的节点内容的最大容量</param>
/// <param name="IpFileName">文件的全路径</param>
/// <returns></returns>
[System.Runtime.InteropServices.DllImport("kernel32")]
static extern int GetPrivateProfileString(string IpAppName, string IpKeyName, string IpDefault, StringBuilder IpReturnString, int nSize, string IpFileName);
/// <summary>
/// 对INI文件进行写入操作
/// </summary>
/// <param name="mpAppName">INI文件内部根节点的值</param>
/// <param name="mpKeyName">将要修改的标记名称</param>
/// <param name="mpDefault">想要修改的内容</param>
/// <param name="mpFileName">INI文件的全路径</param>
/// <returns></returns>
[System.Runtime.InteropServices.DllImport("kernel32")]
static extern long WritePrivateProfileString(string mpAppName, string mpKeyName, string mpDefault, string mpFileName);
}
#endregion
调用方法:
例如config.ini文件里面内容为:
[URLConfig]
url = www.csdn.net
url2= /baike/
url3= /map/
读配置文件:
string filePath = System.Environment.CurrentDirectory + @"/config.ini"; //设置config的绝对路径
string url = INIHelper.ReadFromINI(filePath, "URLConfig", "url").Replace(" ", "");
写配置文件:
string filePath = System.Environment.CurrentDirectory + @"/config.ini"; //设置config的绝对路径
INIHelper.WriteToINI(filePath, "URLConfig", "Url", "www.eastcoms.com");