1.前言:
本範例介紹另一種讀取ini檔案的方法,利用StreamReader及Regular Expression的方法讀取檔案內容。
2.說明:
利用Windows API來讀取標準的ini檔案可參考
http://einboch.pixnet.net/blog/post/250128728
程式碼:
static void Main(string[] args)
{
//檔案位置與名稱
string fileName = @"d:\tmp\myConfig.ini";
//呼叫方法
string ValueString = GetKeyValueString(fileName, "Database", "server");
Console.WriteLine(ValueString);
Console.ReadLine();
}
private static string GetKeyValueString(string fileName, string Section, string Key)
{
StringBuilder value = new StringBuilder(255);
bool hasSection = false;
//開啟IO串流
StreamReader sr = new StreamReader(fileName, Encoding.UTF8);
while (true)
{
string s = sr.ReadLine();
//空值或空字串判斷
if (s == null || s == "")
{
continue;
}
//以;或是#開頭作註解的判斷
if (Regex.Match(s, @"^(;|#).*$").Success)
{
continue;
}
//讀取[Section]
if (Regex.Match(s, @"^\[.*\]").Success)
{
//判斷Section名稱是否符合
if (Regex.Match(s, Section).Success)
{
hasSection = true;
}
}
//如果Section存在,才去判斷Key
if (hasSection)
{
string[] KeyValue = s.Split('=');
//判斷Key名稱是否符合
if (Regex.Match(KeyValue[0].Trim(), Key).Success)
{
value.Append(KeyValue[1].Trim());
break;
}
}
}
//關閉IO串流
sr.Close();
return value.ToString();
}
圖例:
文章標籤
全站熱搜
