110,534
社区成员
发帖
与我相关
我的任务
分享
class TA_INIDocument
{
public TA_INIDocument(){}
public TA_INIDocument(string path):this(){
//ini文件读路径,然后ReadAllText( ),等等其它操作,构造函数在原有基础上重载
}
#region TA_INIDocument
Dictionary<string, System.Collections.Specialized.NameValueCollection> data =
new Dictionary<string, NameValueCollection>();
static readonly System.Text.RegularExpressions.Regex regRemoveEmptyLines =
new System.Text.RegularExpressions.Regex
(
@"(\s*;[\d\D]*?\r?\n)+|\r?\n(\s*\r?\n)*",
System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.Compiled
);
static readonly System.Text.RegularExpressions.Regex regParseIniData =
new System.Text.RegularExpressions.Regex
(
@"
(?<IsSection>
^\s*\[(?<SectionName>[^\]]+)?\]\s*$
)
|
(?<IsKeyValue>
^\s*(?<Key>[^(\s*\=\s*)]+)?\s*\=\s*(?<Value>[\d\D]*)$
)",
System.Text.RegularExpressions.RegexOptions.Compiled |
System.Text.RegularExpressions.RegexOptions.IgnoreCase |
System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace
);
public void ReadAllText( )
{
string fullpath = Application.StartupPath + "\\" + EMPSystemConfigurations.INI_CFG_PATH;
data.Clear();
string lastSection = string.Empty;
data.Add(lastSection, new NameValueCollection());
string iniData;
using (StreamReader reader = new StreamReader(fullpath))
{
iniData = reader.ReadToEnd();
}
iniData = regRemoveEmptyLines.Replace(iniData, "\n");
string[] lines = iniData.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lines)
{
Match m = regParseIniData.Match(s);
if (m.Success)
{
if (m.Groups["IsSection"].Length > 0)
{
string sName =m.Groups["SectionName"].Value.ToLowerInvariant();
if (lastSection != sName)
{
lastSection = sName;
if (!data.ContainsKey(sName))
{
data.Add(sName, new NameValueCollection());
}
}
}
else if (m.Groups["IsKeyValue"].Length > 0)
{
data[lastSection].Add(m.Groups["Key"].Value,m.Groups["Value"].Value);
}
}
}
}
public NameValueCollection this[string section]
{
get
{
section = section.ToLowerInvariant();
if (!data.ContainsKey(section))
data.Add(section, new NameValueCollection());
return data[section];
}
}
//this当做索引器,直接取值
public string this[string section, string key]
{
get
{
return this[section][key];
}
//set
//{
// this[section][key] = value;
//}
}
#endregion
}