C#操作ini文件
有时候在用C#开发时会需要在本地存储一些简单的数据或者配置信息类的,此时会想起使用ini文件去完成。
使用的基本原理
实例代码
下面是我自己写的简单的类:
引用:using System.Runtime.InteropServices;
class CIni
{
private string Path;
public CIni(string path)
{
this.Path = path;
}
// function:写入INI文件
// param :节点名称、键、值、文件路径
// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
// function:读取INI文件
// param :节点名称、键、值、对象、字节大小、文件路径
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
// 接口:写入ini
public void WriteContentValue(string section, string key, string iValue)
{
WritePrivateProfileString(section, key, iValue, this.Path);
}
// 接口:读取INI文件中的内容
public string ReadContentValue(string Section, string key)
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, key, "", temp, 1024, this.Path);
return temp.ToString();
}
}
使用
下面是使用示例:
引用:using System.IO;
private static string FileName = Application.StartupPath + "\\TestInfo.ini";
// 读取
if (File.Exists(FileName))
{
common.CIni P_Ini = new common.CIni(FileName);
DevName = P_Ini.ReadContentValue("DevName", "DevNameValue");
}
else
{
MessageBox.Show("本地无文件!");
}
// 写入
if (File.Exists(FileName))
{
CIni P_Ini = new CIni(FileName);
P_Ini.WriteContentValue("DevName", "DevNameValue", DevName);
}
else
{
using (FileStream myFs = new FileStream(FileName, FileMode.Create)) { }
CIni P_Ini = new CIni(FileName);
P_Ini.WriteContentValue("DevName", "DevNameValue", "示例");
}
因为在类里读取和写入时没有做安全检查,所以在使用时要记得做安全检查,至少先去判文件是否存在,然后才能进行后续操作。
以上内容均属于个人使用时的简单示例,项目中要考虑更多的入口和出口检查,实例创建等要以具体项目中去做。