封裝 kernel32.dll 的 WritePrivateProfileString 與 GetPrivateProfileString 函式,提供類型安全的讀寫介面。
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 strFilePath;
public string FilePath { get { return strFilePath; } set { strFilePath = value; } }
public INIFILE() { }
public INIFILE(string filePath) { this.strFilePath = filePath; }
public void WriteValue(string section, string key, string value)
{
if (FilePath.Length == 0) throw new Exception("未設定檔案路徑");
WritePrivateProfileString(section, key, value, this.FilePath);
}
public string ReadValue(string section, string key)
{
if (FilePath.Length == 0) throw new Exception("未設定檔案路徑");
StringBuilder sb = new StringBuilder();
GetPrivateProfileString(section, key, "", sb, 255, this.FilePath);
return sb.ToString();
}
}
protected void Page_Load(object sender, EventArgs e)
{
INIFILE ini = new INIFILE();
ini.FilePath = Request.PhysicalApplicationPath + "ini.ini";
// 讀取
string val = ini.ReadValue("Annabelle", "Time");
Response.Write("讀取值:" + val + "
");
// 寫入
ini.WriteValue("Annabelle", "Time", "0");
val = ini.ReadValue("Annabelle", "Time");
Response.Write("寫入後讀取:" + val);
}
web.config、appsettings.json 或資料庫儲存設定,INI 適用於相容舊系統或特殊需求。