一、INI文件读取专用
- public class IniFile
- {
- /// <summary>
- /// 读取INI文件专用类
- /// </summary>
- private Hashtable iniFile = new Hashtable();
- public int Count { get { return iniFile.Count; } }
- public string this[string IndexKey] { get { return iniFile[IndexKey].ToString(); } }
- /// <summary>
- /// 读取指定INI文件中的配置信息
- /// </summary>
- /// <param name="file">配置文件的完整路径名</param>
- /// <param name="section">配置文件中的节名</param>
- public IniFile(string file, string section)
- {
- string Section = "[" + section + "]";
- LoadIniFile(file, Section);
- //如果SpecialIniFilePath不为空,则从SpecialIniFilePath指定的文件中读取配置信息
- if (iniFile.Count>0 && iniFile.Contains("SpecialIniFilePath"))
- {
- string path = this["SpecialIniFilePath"].Trim();
- if (path != "") LoadIniFile(path, Section);
- }
- }
- private void LoadIniFile(string filePath, string Section)
- {
- try
- {
- StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default);
- string readLine = null;
- bool readEnd = false;
- string[] keyWord;
- while ((readLine = sr.ReadLine()) != null)
- {
- if (readLine == Section) //是指定的节,则开始读取配置信息
- {
- while ((readLine = sr.ReadLine()) != null)
- {
- if (readLine != "") //跳过空行
- {
- if (readLine.Substring(0, 1) == "[") //是另一新节,则结束本次的读取
- {
- readEnd = true;
- break;
- }
- keyWord = readLine.Split('=');
- iniFile[keyWord[0].Trim()] = keyWord[1];
- }
- }
- }
- if (readEnd == true) break;
- }
- sr.Close();
- }
- catch
- {
- iniFile.Clear();
- }
- }
- }
二、INI文件样例
[DBA]
SpecialIniFilePath=
ServerName=AppSrv
DatabaseName=AppDb
UserID=07AIQY6Vow5xph2075bjrz7uPX4WOG7767CKS08Tqy3vnf5013dlt19sRZ2UME67
UserPassword=066EMU2Zs91tld929E3fnv3yT80SKC67667GOW4Xu7zrjb49653hpx5wV6YQIA77
Timeout=90
三、使用方法
- IniFile ini = new IniFile(System.Windows.Forms.Application.StartupPath + @"/Appcfg.ini", "Appcfg");
- if (ini.Count>0)
- {
- _server = ini["ServerName"];
- _database = ini["DatabaseName"];
- _uid = ini["UserID"];
- _uid = Crypt.RndDecrypt("uid", _uid); //解密
- _pwd = ini["UserPassword"];
- _pwd = Crypt.RndDecrypt("pwd", _pwd); //解密
- _timeout = ini["Timeout"];
- }