c#读写ini文件

通过调用win32 api可以直接读写ini文件

写了一个助手类方便操作:

using System;
using System.Text;
using System.Runtime.InteropServices;

public static class IniFileHelper
{
    [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);

    public static void Write(string section, string key, string val, string filePath)
    {
        WritePrivateProfileString(section, key, val, filePath);
    }

    public static string Read(string section, string key, string filePath)
    {
        var stringBuilder = new StringBuilder(255);
        GetPrivateProfileString(section, key, string.Empty, stringBuilder, 255, filePath);
        return stringBuilder.ToString();
    }
}
IniFileHelper

 

测试代码:

static void Main(string[] args)
{
    IniFileHelper.Write("BaseSetting", "Language", "en_us", "./Config.ini");
    IniFileHelper.Write("Sound", "Enable", "True", "./Config.ini");
    IniFileHelper.Write("Sound", "Volume", "100", "./Config.ini");
}

 

 

运行结果:

c#读写ini文件_第1张图片

 

 

读取测试:

你可能感兴趣的:(c#读写ini文件)