C# 存取ini檔

C# Class 存取 ini 內容,直接用就好。

ini內容

[session name]

key1 = value1

key2 = value2

傳入ini 檔案名稱,ini 檔案放在執行程序相同目錄下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{
    using System.Runtime.InteropServices;
    using System.IO;

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

        private string filepath;

        public IniFile(string fileName)
        {
            this.filepath = Path.GetFullPath(fileName); 
        }

        public void WriteIni(string section, string key, string val)
        {
            WritePrivateProfileString(section, key, val, filepath);
        }

        public string ReadIni(string section, string key)
        {
            StringBuilder temp = new StringBuilder(255);
            GetPrivateProfileString(section, key, "", temp, 255, filepath);
            return temp.ToString();
        }
    }
}