C#之配置文件Ini

简介: C#之配置文件Ini

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文件内容如下:


去.png



 


相关文章
|
9月前
|
存储 API C语言
ini
ini
125 0
|
安全 关系型数据库 PHP
|
Shell 数据安全/隐私保护
|
应用服务中间件
|
XML JSON Java
04SpringBoot配置文件
04SpringBoot配置文件
54 0
FastMM配置文件详解
FastMM最新版本提供了中文语言包,可方便国内使用。下载地址为 http://sourceforge.net/projects/fastmm/ 配置文件为:FastMM4Options.
1096 0
|
应用服务中间件 nginx Python
|
关系型数据库 Apache 数据安全/隐私保护

热门文章

最新文章