在作應用系統開發時,管理配置是必不可少的。例如數據庫服務器的配置、安裝和更新配置等等。由于Xml的興起,現在的配置文件大都是以xml文檔來存儲。比如Visual Studio.Net自身的配置文件Mashine.config,Asp.Net的配置文件Web.Config,包括我在介紹Remoting中提到的配置文件,都是xml的格式。
傳統的配置文件ini已有被xml文件逐步代替的趨勢,但對于簡單的配置,ini文件還是有用武之地的。ini文件其實就是一個文本文件,它有固定的格式,節Section的名字用[]括起來,然后換行說明key的值:
[section]
key=value
如數據庫服務器配置文件:
DBServer.ini
1
2
3
4
5
6
|
[Server] Name=localhost [DB] Name=NorthWind [User] Name=sa |
在C#中,對配置文件的讀寫是通過API函數來完成的,代碼很簡單:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
using System; using System.Text; using System.IO; using System.Runtime.InteropServices; namespace PubOp { public class OperateIniFile { #region API函數聲明 [DllImport( "kernel32" )] //返回0表示失敗,非0為成功 private static extern long WritePrivateProfileString( string section, string key, string val, 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 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()的參數。
Section參數、Key參數和IniFilePath不用再說,Value參數表明key的值,而這里的NoText對應API函數的def參數,它的值由用戶指定,是當在配置文件中沒有找到具體的Value時,就用NoText的值來代替。
NoText 可以為null或""
總結
以上所述是小編給大家介紹的C#中讀寫INI配置文件的方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
原文鏈接:https://blog.csdn.net/xishining/article/details/80912819