C# 读写.ini配置文件

`class Ini {
    // 声明INI文件的写操作函数 WritePrivateProfileString()
    [System.Runtime.InteropServices.DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

    // 声明INI文件的读操作函数 GetPrivateProfileString()
    [System.Runtime.InteropServices.DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

    public static bool Write(string section, string key, string value, string sPath) {
        // section=配置节,key=键名,value=键值,path=路径
        long bOK = WritePrivateProfileString(section, key, value, sPath);
        return true;

    }
    public static string Read(string section, string key, string defaultVal, string sPath) {
        // 每次从ini中读取多少字节
        System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

        // section=配置节,key=键名,defaultVal=当没有读到值时返回模式值,temp=上面,path=路径;
        GetPrivateProfileString(section, key, defaultVal, temp, 255, sPath);
        return temp.ToString();
    }
}`

config.ini文档格式
[section1]
key1=value1
key2=value2
key3=value3
key4=value4
[section2]
key1=value1
key2=value2
key3=value3
key4=value4
key5=value5
key6=value6
key7=value7

猜你喜欢

转载自blog.csdn.net/weixin_44480111/article/details/86240974