1、IniConfig类
class IniConfig
{
public string path="./log.ini"; //INI文件名
//声明写INI文件的API函数
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
//声明读INI文件的API函数
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
//类的构造函数,传递INI文件的路径和文件名
//public IniConfig(string INIPath)
//{
// path = INIPath;
//}
//写INI文件
public void IniWriteValue(string Section, string Key, string Value)
{
if (!File.Exists(path))
{
//File.Create(path);
FileStream fs = new FileStream(path, FileMode.CreateNew);
fs.Close();
}
WritePrivateProfileString(Section, Key, Value, path);
}
//读取INI文件
public string IniReadValue(string Section, string Key)
{
if (!File.Exists(path))
{
return "";
}
StringBuilder temp = new StringBuilder(4096);
int i = GetPrivateProfileString(Section, Key, "", temp, 4096, path);
return temp.ToString();
}
}
其中注意两点:
- 如果软件只有一个ini文件,那么IniConfig里面的path可以设置为固定的路径,如果炫耀读取不同的ini文件,则使用注释掉的public IniConfig(string INIPath)的。实例化的时候加上路径即可IniConfig logini = new IniConfig("logs.ini");
- 在写操作时,如果没有该ini配置文件应该创建一个再写,若使用File.Create(path);创建之后不能立马写入,所以使用FileStream fs = new FileStream(path, FileMode.CreateNew);fs.Close();创建ini文件。
2、读取ini
IniConfig iniConfig_log = new IniConfig();
string imgs_dir = iniConfig_log.IniReadValue("objectTest", "imgDir");
if (!String.IsNullOrEmpty(imgs_dir) & Directory.Exists(imgs_dir))
{
Console.WriteLine(imgs_dir);
}
3、写入ini
string onnx_path = "C:/Users/deploy.onnx";
iniConfig_log.IniWriteValue("objectTest", "onnxPath", onnx_path);
示例的ini文件内容如下: