C# 读写.ini配置文件

倾然丶 夕夏残阳落幕 提交于 2019-11-29 22:07:37
`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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!