INI形式のファイルを読み込み、読み込んだセクション・キー・値を一覧にして表示する。
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
static void Main(string[] args)
{
string iniFile = @"test.ini";
StreamReader reader = null;
Dictionary<string, Dictionary<string, string>> sections = new Dictionary<string, Dictionary<string, string>>();
// セクション名が明示されていない先頭部分のセクション名を""として扱う
sections.Add(string.Empty, new Dictionary<string, string>());
try
{
reader = new StreamReader(iniFile, Encoding.Default);
Regex regexSection = new Regex(@"^\[(?<section>[^\]]+)\].*$", RegexOptions.Singleline);
Regex regexKeyValue = new Regex(@"^(?<key>[^=]+)=(?<value>.*)$", RegexOptions.Singleline);
Match match;
string currentSection = string.Empty;
for (; ; )
{
string line = reader.ReadLine();
if (line == null) break;
// コメント行は読み飛ばす
if (line.StartsWith(";")) continue;
// 空行は読み飛ばす
if (string.Empty.Equals(line.Trim())) continue;
// "キー=値"の形式にマッチするか
match = regexKeyValue.Match(line);
if (match.Success)
{
string key = match.Groups["key"].Value.Trim();
string value = match.Groups["value"].Value.Trim();
if (sections[currentSection].ContainsKey(key))
{
// キーが存在する場合は上書き
sections[currentSection][key] = value;
}
else
{
// キーを追加する
sections[currentSection].Add(key, value);
}
// 次の行を読む
continue;
}
// "[セクション]"の形式にマッチするか
match = regexSection.Match(line);
if (match.Success)
{
currentSection = match.Groups["section"].Value;
if (!sections.ContainsKey(currentSection))
{
// 新しいセクションを追加する
sections.Add(currentSection, new Dictionary<string, string>());
}
// 次の行を読む
continue;
}
}
}
finally
{
if (reader != null) reader.Close();
}
// 読み込んだ結果を表示する
foreach (KeyValuePair<string, Dictionary<string, string>> section in sections)
{
Console.WriteLine("[{0}]", section.Key);
foreach (KeyValuePair<string, string> entry in section.Value)
{
Console.WriteLine(" {0}={1}", entry.Key, entry.Value);
}
}
}
例としてこのようなiniファイルの場合、
; sample ini file username=test password=xxxx ; setting for screen [screen] screenmode = fullscreen screensize = 640x480 refresh-rate = 60Hz ; setting for input [input] shot = 0 bomb = 1 skip = 2 cancel = 3 [screen] screensize = 800x600
次のような実行結果となる。
[] username=test password=xxxx [screen] screenmode=fullscreen screensize=800x600 refresh-rate=60Hz [input] shot=0 bomb=1 skip=2 cancel=3