首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 讀寫 INI 設定檔範例(P/Invoke 封裝 Kernel32 API)

     編輯:關於ASP.NET

核心類別 INIFILE.cs

封裝 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();
    }
}

頁面使用範例 INIFile.aspx.cs

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); }

注意事項

  • INI 檔需置於網站實體路徑下,且 ASP.NET 執行身分需具備寫入權限。
  • 現代 ASP.NET 應優先考慮 web.config、appsettings.json 或資料庫儲存設定,INI 適用於相容舊系統或特殊需求。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved