INI文件读取帮助
项目中时常会用到不少的外部配置参数,又或者对一些CODE预先定义.使用INI文件来存储不失为一个好办法
public class INIHelper
{
/// <summary>
/// 读取INI文件专用类
/// </summary>
private bool succeeded = false;
private Hashtable cfgParam = new Hashtable();
public bool Succeeded { get { return succeeded; } }
public string this[string ParamName]
{
get
{
if (cfgParam.ContainsKey(ParamName))
return cfgParam[ParamName].ToString();
else
return "";
}
}
public int Length
{
get { return cfgParam.Count; }
}
/// <summary>
/// 读取指定INI文件中的配置信息
/// </summary>
/// <param name="file">配置文件的完整路径名</param>
/// <param name="section">配置文件中的节名</param>
public DbConfig(string file, string section)
{
string Section = "[" + section + "]";
string fileName = file.Substring(file.LastIndexOf('\\') + 1);
GetInitializeConfig(file, Section);
//如果MainSysinfoPath不为空,则从MainSysinfoPath指定的文件中读取配置信息
if (this.succeeded && cfgParam.Contains("MainSysinfoPath"))
{
string path = this["MainSysinfoPath"].TrimEnd('\\'); //允许路径尾部带反斜杆“\”或不带反斜杆“\”
if (path != "") GetInitializeConfig(path + @"\" + fileName, Section);
}
}
private void GetInitializeConfig(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('=');
cfgParam[keyWord[0].Trim()] = keyWord[1].Trim();
}
}
}
if (readEnd == true) break;
}
sr.Close();
succeeded = true;
}
catch
{
succeeded = false;
}
}
}
读取速度不错....当然别弄个几百M的配置文件哦....