C#讀寫INI設定檔

來源:互聯網
上載者:User

在做應用系統開發時,管理配置是必不可少的。例如資料庫伺服器的配置、安裝和更新配置等等。由於Xml的興起,現在的設定檔大都是以xml文檔來儲存。比如Visual Studio.Net自身的設定檔Mashine.config,Asp.Net的設定檔Web.Config,包括我在介紹Remoting中提到的設定檔,都是xml的格式。

傳統的設定檔ini已有被xml檔案逐步代替的趨勢,但對於簡單的配置,ini檔案還是有用武之地的。ini檔案其實就是一個文字檔,它有固定的格式,節Section的名字用[]括起來,然後換行說明key的值:
[section]
key=value

如資料庫伺服器設定檔:

DBServer.ini

[Server]
Name=localhost
[DB]
Name=NorthWind
[User]
Name=sa

在C#中,對設定檔的讀寫是通過API函數來完成的,代碼很簡單:

INI設定檔操作類
public class IniTool
    {
        #region ---API函式宣告---

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key,
            string value, string filePath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section,string key,
            string def,StringBuilder retVal,int size,string filePath);

        #endregion

        #region ---對Ini檔案操作(讀寫)---

        public static string ReadIniData(string section,string key,string defValue,string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder str = new StringBuilder(1024);
                GetPrivateProfileString(section, key, defValue, str, 1024, iniFilePath);
                return str.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        public static bool WriteIniData(string section, string key, string value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long result = WritePrivateProfileString(section, key, value, iniFilePath);
                return result == 0 ? false : true;
            }
            return false;
        }

        #endregion
    }

簡單說明以下方法WriteIniData()和ReadIniData()的參數。

Section參數、Key參數和IniFilePath不用再說,Value參數表明key的值,而這裡的NoText對應API函數的def參數,它的值由使用者指定,是當在設定檔中沒有找到具體的Value時,就用NoText的值來代替。

出處:http://kb.cnblogs.com/page/43446/

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.