C# 讀寫.ini配置檔案
阿新 • • 發佈:2019-01-11
`class Ini { // 宣告INI檔案的寫操作函式 WritePrivateProfileString() [System.Runtime.InteropServices.DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); // 宣告INI檔案的讀操作函式 GetPrivateProfileString() [System.Runtime.InteropServices.DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath); public static bool Write(string section, string key, string value, string sPath) { // section=配置節,key=鍵名,value=鍵值,path=路徑 long bOK = WritePrivateProfileString(section, key, value, sPath); return true; } public static string Read(string section, string key, string defaultVal, string sPath) { // 每次從ini中讀取多少位元組 System.Text.StringBuilder temp = new System.Text.StringBuilder(255); // section=配置節,key=鍵名,defaultVal=當沒有讀到值時返回模式值,temp=上面,path=路徑; GetPrivateProfileString(section, key, defaultVal, temp, 255, sPath); return temp.ToString(); } }`
config.ini文件格式
[section1]
key1=value1
key2=value2
key3=value3
key4=value4
[section2]
key1=value1
key2=value2
key3=value3
key4=value4
key5=value5
key6=value6
key7=value7