[C#]INI文件控制类

时间:2021-05-13 18:26:38

INI文件常用于保存各类设置或本地化文本,大概格式如下:

[Section]
key=value

然而.NET框架似乎并没有提供一个实用的工具来操作它,或许是因为MS想让我们都使用Settings类控制的config文件?
但是出于多种原因,我还是不太喜欢用Settings类以及这个XML格式的config文件。

幸运的是,有两个Win32API可以帮我们完成INI文件的控制:
WritePrivateProfileString
GetPrivateProfileString

但是非常尴尬的是这俩一个能写入中文,另一个却读不好中文。。。

于是只好自己动手丰衣足食了,谨记于此以备日后又有所需:

 abstract class ConfigurationBase
{
public abstract string Path { get; } public abstract string Section { get; } /// <summary>
/// 指定好编码格式就能支持各种语言文字了
/// </summary>
private readonly Encoding encoding = Encoding.UTF8; public void Clear()
{
File.Delete(Path);
} public void Save()
{
File.WriteAllLines(Path, lines.ToArray(), encoding);
} private readonly List<string> lines; protected ConfigurationBase()
{
if (File.Exists(Path))
{
lines = new List<string>(
File.ReadAllLines(Path, encoding));
}
else
{
lines = new List<string>();
}
} protected string Get(string key, string defaultVal)
{
if (lines.Count != )
{
string sectionLine = String.Format("[{0}]", Section);
string keyLine = String.Format("{0}=", key);
Regex otherSection = new Regex(@"^\[[^\]+]\]$", RegexOptions.Compiled); bool inSection = false;
foreach (string line in lines)
{
if (sectionLine == line)
{
inSection = true;
}
else if (otherSection.IsMatch(line))
{
if (inSection) break;
}
else if (inSection && line.StartsWith(keyLine))
{
return line.Substring(keyLine.Length);
}
}
}
return defaultVal;
} protected void Set(string key, string value)
{
string sectionLine = String.Format("[{0}]", Section);
string keyLine = String.Format("{0}=", key);
Regex otherSection = new Regex(@"^\[[^\]+]\]$", RegexOptions.Compiled);
string valueLine = String.Format("{0}{1}", keyLine, value); bool inSection = false;
for (int i = ; i < lines.Count; i++)
{
if (sectionLine == lines[i])
{
inSection = true;
}
else if (otherSection.IsMatch(lines[i]))
{
if (inSection)
{
lines.Insert(i, valueLine);
break;
}
}
else if (inSection && lines[i].StartsWith(keyLine))
{
lines[i] = valueLine;
}
}
if (inSection)
{
lines.Add(valueLine);
}
else
{
lines.Add(sectionLine);
lines.Add(valueLine);
}
}
}