欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【C#】C# 读写ini配置文件 WritePrivateProfileString和GetPrivateProfileString

程序员文章站 2022-06-12 08:57:25
...
[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);

封装接口

/// <summary>
/// 读取ini配置文件
/// </summary>
/// <param name="Section">段</param>
/// <param name="Key">键名</param>
/// <param name="def">默认值</param>
/// <param name="filePath">文件路径</param>
/// <returns>读出内容</returns>
public static string ReadValueFromIniFile(string Section, string Key, string def, string filePath)
{
    StringBuilder temp = new StringBuilder(255);
    int i = GetPrivateProfileString(Section, Key, def, temp, 255, filePath);
    return temp.ToString();
}

/// <summary>
/// 写入ini配置文件
/// </summary>
/// <param name="Section">段</param>
/// <param name="Key">键名</param>
/// <param name="Value">键值</param>
/// <param name="filePath">文件路径</param>
public static void WriteValueFromIniFile(string Section, string Key, string Value, string filePath)
{
    WritePrivateProfileString(Section, Key, Value, filePath);
}
static void Main(string[] args)
{
    //写入
    WriteValueFromIniFile("Section", "Name", "GreAmbWang", iniFilePath);
    WriteValueFromIniFile("Section", "Pwd", "123456", iniFilePath);

    //读取
    string name = ReadValueFromIniFile("Section", "Name", "def", iniFilePath);
    string pwd = ReadValueFromIniFile("Section", "Pwd", "null", iniFilePath);

    Console.Write("Name = " + name + "\r\n" + "Pwd = " + pwd);

    Console.ReadKey();
}

文件格式
【C#】C# 读写ini配置文件 WritePrivateProfileString和GetPrivateProfileString
输出
【C#】C# 读写ini配置文件 WritePrivateProfileString和GetPrivateProfileString