C# ini文件读写简单封装

一、故事线

ini文件是非常好用的配置文件,通过系统api可以方便的管理参数,本文介绍一下c#下文件读写方法。

二、文件格式

通常ini文件是这样的格式:

[section1]

key1=value1

key2=value2

[section2]

key3=value3

key4=value4

section标识块,一个简单的分组

key~value对应的键值对

三、系统API

[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section
    , string key
    , string val
    , string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section
    , string key
    , string def
    , StringBuilder retVal
    , int size
    , string filePath);

DLLImport引用系统API

三、用法介绍(封装)

public static string IniReadValue(string section
            , string key
            , string iniPath)
{
    StringBuilder temp = new StringBuilder(500);
    int i = GetPrivateProfileString(section, key, "", temp, 500, iniPath);
    return temp.ToString();
}

public static void IniWriteValue(string section
       , string key
            , string value
            , string iniPath)
{
  WritePrivateProfileString(section, key, value, iniPath);
}

这个封装我也一直在用,非常方便。

posted @ 2017-08-31 12:31  sunlyk  阅读(441)  评论(0编辑  收藏  举报