c#讀寫ini檔案

weixin_34162629發表於2016-01-22

通過呼叫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");
}

 

 

執行結果:

 

 

讀取測試:

相關文章