04-002 Configuration 之 IniFileConfigurationSource
Posted on 2015-03-16 14:24 DotNet1010 阅读(369) 评论(0) 收藏 举报ini 文件中的注释有三种符号 ; # / 以这三种符号开头的行 为注释
方括号中的内容相当于是前缀
看一些 ini 文件的例子 例子1:
; last modified 1 April 2001 by John Doe
[owner]
name=John Doe
organization=Acme Widgets Inc.
[database]
; use IP address in case network name resolution is not working
server=192.0.2.62
port=143
file="payroll.dat"
例子2:boot.ini
[boot loader]
timeout=40
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Professional" /fastdetect
例子3:
; for 16-bit app support
[drivers]
wave=mmdrv.dll
timer=timer.drv
;下面的一行没有任何作用
[mci]
;下面的一行没有任何作用
[driver32]
[386enh]
woafont=dosapp.FON
# 上面的一行 相当于 386enh:woafont=dosapp.FON
EGA80WOA.FON=EGA80WOA.FON
# 上面的一行 相当于 386enh:EGA80WOA=EGA80WOA.FON
EGA40WOA.FON=EGA40WOA.FON
CGA80WOA.FON=CGA80WOA.FON
结合上述的例子 看一下实现的代码:
internal void Load(Stream stream)
{
var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
using (var reader = new StreamReader(stream))
{
var sectionPrefix = string.Empty;
while (reader.Peek() != -1)
{
var rawLine = reader.ReadLine();
var line = rawLine.Trim();
// Ignore blank lines
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
// Ignore comments
if (line[0] == ';' || line[0] == '#' || line[0] == '/')
{
continue;
}
// [Section:header]
if (line[0] == '[' && line[line.Length - 1] == ']')
{
// remove the brackets
sectionPrefix = line.Substring(1, line.Length - 2) + ":";
continue;
}
// key = value OR "value"
int separator = line.IndexOf('=');
if (separator < 0)
{
throw new FormatException(Resources.FormatError_UnrecognizedLineFormat(rawLine));
}
string key = sectionPrefix + line.Substring(0, separator).Trim();
string value = line.Substring(separator + 1).Trim();
// Remove quotes
if (value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"')
{
value = value.Substring(1, value.Length - 2);
}
if (data.ContainsKey(key))
{
throw new FormatException(Resources.FormatError_KeyIsDuplicated(key));
}
data[key] = value;
}
}
ReplaceData(data);
}
浙公网安备 33010602011771号