public IniFile(string path)
{
_content = new Dictionary<string, Dictionary<string, string>>();
_path = path;
// Create
if (!File.Exists(path))
{
File.CreateText(path).Close();
return;
}
// Open
bool sectionFound = false;
Dictionary<string, string> currentSection = null;
string data = null;
using (StreamReader sr = new StreamReader(path))
{
data = sr.ReadToEnd();
}
if (string.IsNullOrEmpty(data)) return;
string[] lines = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
if (lines == null || lines.Length == 0) return;
foreach (string l in lines)
{
string line = l.Trim();
// Ignore empty line
if (line == string.Empty) continue;
// Ignore remark line
bool isRemarkLine = false;
foreach (string remarkMarker in COMMENT_MARKERS)
{
if (line.StartsWith(remarkMarker))
{
isRemarkLine = true;
break;
}
}
if (isRemarkLine) continue;
// Try matching section or key/value pair
Match matchSection = Regex_Section.Match(line);
Match matchKeyValue = Regex_KeyValue.Match(line);
if (!sectionFound && matchKeyValue.Success)
{
throw new InvalidDataException("A key/value pair must occur after a section marker.");
}
if (matchSection.Success)
{
sectionFound = true;
string section = matchSection.Groups[1].Value;
if (_content.ContainsKey(section))
{
currentSection = _content[section];
}
else
{
currentSection = new Dictionary<string, string>();
_content.Add(section, currentSection);
}
}
else if (matchKeyValue.Success)
{
string key = matchKeyValue.Groups[1].Value;
string value = matchKeyValue.Groups[2].Value;
if (currentSection.ContainsKey(key))
{
currentSection[key] = value;
}
else
{
currentSection.Add(key, value);
}
}
}
}