C#讀寫INI設定檔

來源:互聯網
上載者:User
Ini設定檔可以使用讀寫文本的方法處理,也可以使用API進行操作。 

Ini設定檔的格式如下: 
[主鍵名] 
子鍵名1 = 索引值1 
子鍵名2 = 索引值2 
子鍵名3 = 索引值3 
…………………… 
子鍵名n = 索引值n 

Kernel32.dll中提供了GetPrivateProfileString和WritePrivateProfileString兩個方法進行Ini檔案的讀寫操作: 

public class RWIniFile{     [ DllImport ( "kernel32" ) ]         private static extern int GetPrivateProfileString ( string section ,string key , string def , System.Text.StringBuilder retVal ,int size , string filePath ) ;           //參數說明:section:INI檔案中的段落名稱;key:INI檔案中的關鍵字;def:無法讀取時候時候的預設數值;retVal:讀取數值;size:數值的大小;filePath:INI檔案的完整路徑和名稱。             //讀取索引值         public static string ReadIni(string 主鍵名,string 子鍵名,string 預設索引值,int 數值大小,string 檔案路徑)                                 {             string m_ret=預設索引值;             try             {                 System.Text.StringBuilder 傳回值=new System.Text.StringBuilder(預設索引值);                 GetPrivateProfileString(主鍵名,子鍵名,預設索引值,傳回值,數值大小,檔案路徑);                 m_ret=傳回值.ToString();             }             catch             {                 m_ret=預設索引值;             }             return m_ret;         }        [ DllImport ( "kernel32" ) ]         private static extern long WritePrivateProfileString ( string section , string key , string val , string filePath ) ;     //參數說明:section:INI檔案中的段落;key:INI檔案中的關鍵字;val:INI檔案中關鍵字的數值;filePath:INI檔案的完整的路徑和名稱。        //寫入索引值         public static bool WriteIni(string 主鍵名,string 子鍵名,string 數值,string 檔案路徑)                                                 {             bool m_ret=true;             try             {                 WritePrivateProfileString(主鍵名,子鍵名,數值,檔案路徑);             }             catch             {                 m_ret=false;             }             return m_ret;     }}

 


相關文章

聯繫我們

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