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");
}

 

 

运行结果:

 

 

读取测试:

posted @ 2016-01-22 17:56  HONT  阅读(339)  评论(0编辑  收藏  举报