[Implement] Read/Write INI File
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
namespace ReadWrite_INI_File
{
class Program
{
//讀寫INI文件API函數
[System.Runtime.InteropServices.DllImport("kernel32")]
//傳入參數: 1.區段名稱、2.參數名稱、3.預設回傳值(若無符合區段名稱與參數名稱,則回傳預設值)
//4.StringBuffer物件、5.StringBuffer物件大小、6.INI文件完整路徑
private static extern int GetPrivateProfileString(string section, string key, string def,
System.Text.StringBuilder retVal, int size, string filePath);
[System.Runtime.InteropServices.DllImport("kernel32")]
//傳入參數: 1.區段名稱、2.參數名稱、3.參數內容、4.INI文件完整路徑
private static extern long WritePrivateProfileString(string section, string key, string val,
string filePath);
public static string ReadIniValues(string section, string key, string path)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(22000);
int i = GetPrivateProfileString(section, key, "Not Found", sb, 22000, path);
return sb.ToString();
}
static void Main(string[] args)
{
string iniPath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\Setting.ini";
if (System.IO.File.Exists(iniPath))
{
string location = ReadIniValues("Location", "Location1", iniPath);
//result = 10, 50
string size1 = ReadIniValues("FormSize", "Size1", iniPath);
//result = 10
string size2 = ReadIniValues("FormSize", "Size99", iniPath);
//result = Not Found
}
else
{
//寫入時,若INI文件完整路徑中沒有該INI檔,那麼會自動產生一個INI檔
//Insert: 1.區段名稱與參數名稱皆不在INI中,那麼會新增一個該區段名稱,
// 而該區段名稱底下也會新增該參數名稱與參數內容
// 2.區段名稱在INI中,但參數名稱不在INI檔裡,那麼會在該區段名稱
// 底下新增該參數名稱與參數內容
//Update: 區段名稱與參數名稱皆須在INI檔中才會更新,否則會執行Inser動作
WritePrivateProfileString("Location", "Location1", "10,50", iniPath);
WritePrivateProfileString("Location", "Location2", "20,100", iniPath);
WritePrivateProfileString("FormSize", "Size1", "10", iniPath);
WritePrivateProfileString("FormSize", "Size2", "100", iniPath);
}
}
}
}