新聞中心
今天就跟大家聊聊有關(guān)怎么在C#中對INI配置文件進(jìn)行讀寫,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序定制開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了商水免費(fèi)建站歡迎大家使用!
在作應(yīng)用系統(tǒng)開發(fā)時(shí),管理配置是必不可少的。例如數(shù)據(jù)庫服務(wù)器的配置、安裝和更新配置等等。由于Xml的興起,現(xiàn)在的配置文件大都是以xml文檔來存儲。比如Visual Studio.Net自身的配置文件Mashine.config,Asp.Net的配置文件Web.Config,包括我在介紹Remoting中提到的配置文件,都是xml的格式。
傳統(tǒng)的配置文件ini已有被xml文件逐步代替的趨勢,但對于簡單的配置,ini文件還是有用武之地的。ini文件其實(shí)就是一個(gè)文本文件,它有固定的格式,節(jié)Section的名字用[]括起來,然后換行說明key的值:
[section]
key=value
如數(shù)據(jù)庫服務(wù)器配置文件:
DBServer.ini
[Server] Name=localhost [DB] Name=NorthWind [User] Name=sa
在C#中,對配置文件的讀寫是通過API函數(shù)來完成的,代碼很簡單:
using System; using System.Text; using System.IO; using System.Runtime.InteropServices; namespace PubOp { public class OperateIniFile { #region API函數(shù)聲明 [DllImport("kernel32")]//返回0表示失敗,非0為成功 private static extern long WritePrivateProfileString(string section,string key, string val,string filePath); [DllImport("kernel32")]//返回取得字符串緩沖區(qū)的長度 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 NoText,string iniFilePath) { if(File.Exists(iniFilePath)) { StringBuilder temp = new StringBuilder(1024); GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath); return temp.ToString(); } else { return String.Empty; } } #endregion #region 寫Ini文件 public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath) { if(File.Exists(iniFilePath)) { long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath); if(OpStation == 0) { return false; } else { return true; } } else { return false; } } #endregion } }
簡單說明以下方法WriteIniData()和ReadIniData()的參數(shù)。
Section參數(shù)、Key參數(shù)和IniFilePath不用再說,Value參數(shù)表明key的值,而這里的NoText對應(yīng)API函數(shù)的def參數(shù),它的值由用戶指定,是當(dāng)在配置文件中沒有找到具體的Value時(shí),就用NoText的值來代替。
NoText 可以為null或""
看完上述內(nèi)容,你們對怎么在C#中對INI配置文件進(jìn)行讀寫有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
標(biāo)題名稱:怎么在C#中對INI配置文件進(jìn)行讀寫
標(biāo)題URL:http://fisionsoft.com.cn/article/jggohp.html