[轉]C#操作INI檔案

來源:互聯網
上載者:User

標籤:

在很多的程式中,我們都會看到有以.ini為尾碼名的檔案,這個檔案可以很方便的對程式配置的一些資訊進行設定和讀取,比如說我們在做一個程式後台登陸的時候,需要自動登入或者是遠程設定資料庫串連,及儲存密碼設定等等(在Winform程式中),若在ASP.NET程式中有另外的解決方案,此C#操作INI檔案的文章僅在winform程式中進行寫入和讀取操作。

為了方便起見,現在以一個簡單的小執行個體來對C#操作INI檔案進行講解:

表單的大致布局如下

當點擊寫入按鈕的時候就會把文字框中輸入的值寫入到INI檔案中,結果會

當點擊讀取按鈕的時候就會把INI檔案中的節點資訊的值填充到表單中的文字框中

以上就是用C#操作INI檔案的整個流程,現在來介紹後台代碼是怎樣實現的:

在項目名稱空間的上方要添加以下的引用:

using System.Runtime.InteropServices;//引用命名空間

然後再程式的後台聲明一些系統函數的變數,代碼如下

聲明變數  #region "聲明變數"        /// <summary>        /// 寫入INI檔案        /// </summary>        /// <param name="section">節點名稱[如[TypeName]]</param>        /// <param name="key">鍵</param>        /// <param name="val">值</param>        /// <param name="filepath">檔案路徑</param>        /// <returns></returns>        [DllImport("kernel32")]        private static extern long WritePrivateProfileString(string section,string key,string val,string filepath);        /// <summary>        /// 讀取INI檔案        /// </summary>        /// <param name="section">節點名稱</param>        /// <param name="key">鍵</param>        /// <param name="def">值</param>        /// <param name="retval">stringbulider對象</param>        /// <param name="size">位元組大小</param>        /// <param name="filePath">檔案路徑</param>        /// <returns></returns>        [DllImport("kernel32")]        private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retval,int size,string filePath);        private string strFilePath = Application.StartupPath + "\\FileConfig.ini";//擷取INI檔案路徑        private string strSec =""; //INI檔案名稱                 #endregion

先說明下我的INI設定檔是放在程式的Debug檔案夾下的,然後單擊寫入按鈕,在寫入前沒有進行寫入數值的驗證,代碼如下:

寫入事件 //寫入按鈕事件        private void btnWrite_Click(object sender, EventArgs e)        {            try            {                     //根據INI檔案名稱設定要寫入INI檔案的節點名稱                    //此處的節點名稱完全可以根據實際需要進行配置                    strSec = Path.GetFileNameWithoutExtension(strFilePath);                    WritePrivateProfileString(strSec, "Name", txtName.Text.Trim(), strFilePath);                    WritePrivateProfileString(strSec, "Sex", txtSex.Text.Trim(), strFilePath);                    WritePrivateProfileString(strSec, "Age", txtAge.Text.Trim(), strFilePath);                    WritePrivateProfileString(strSec, "Address", txtAddress.Text.Trim(), strFilePath);                    MessageBox.Show("寫入成功");                         }catch(Exception ex){                MessageBox.Show(ex.Message.ToString());                        }        }

 

此時運行此執行個體就會把數值寫入到INI檔案中,寫入的結果就像第二個效果顯示的那樣。然後我們在單擊讀取按鈕事件,把INI檔案中的資訊填充到表單的文字框中,代碼如下:

讀取事件  //讀取按鈕事件        private void btnRead_Click(object sender, EventArgs e)        {            if (File.Exists(strFilePath))//讀取時先要判讀INI檔案是否存在            {                strSec = Path.GetFileNameWithoutExtension(strFilePath);                txtName.Text = ContentValue(strSec, "Name");                txtSex.Text = ContentValue(strSec, "Sex");                txtAge.Text = ContentValue(strSec, "Age");                txtAddress.Text = ContentValue(strSec, "Address");            }            else {                MessageBox.Show("INI檔案不存在");                        }        }

 

在讀取的時候用到了自訂讀取函數的方法,在該方法中調用了系統函數,

}      /// <summary>      /// 自訂讀取INI檔案中的內容方法      /// </summary>      /// <param name="Section">鍵</param>      /// <param name="key">值</param>      /// <returns></returns>        private string ContentValue(string Section,string key) {            StringBuilder temp = new StringBuilder(1024);            GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);            return temp.ToString();        }

 

以上所述的就是簡單的用C#語言操作INI檔案的過程,只用到了系統函數中的兩個(寫入函數和讀取函數)還有其他的函數比如說時刪除INI檔案函數等等,刪除INI檔案函數其實就是把鍵對應的值設定為null就可以了。

自動登入和串連設定都用到了INI檔案,文章到此結束。

參考連結:柄棋先生的博文:《C#操作INI檔案》

[轉]C#操作INI檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.