using System.Collections.Generic;
using System.IO;
namespace Wayne.Lib.IO
{
///
/// Class that manages an Ini-file.
///
public class IniFile
{
private readonly IFileSupport fileSupport;
///
/// Constructor.
///
/// The service locator.
public IniFile(IServiceLocator serviceLocator)
{
fileSupport = serviceLocator.GetService();
Sections = new Dictionary();
}
///
/// The sections of the ini-file.
///
public Dictionary Sections { get; private set; }
///
/// Returns existing or creates a new section.
///
/// The name of the section.
///
public IniFileSection GetSection(string sectionName)
{
IniFileSection section;
if (!Sections.TryGetValue(sectionName, out section))
{
section = new IniFileSection();
Sections.Add(sectionName, section);
}
return section;
}
///
/// Save ini file.
///
/// The name of the file.
public void SaveToFile(string fileName)
{
using (Stream stream = fileSupport.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
foreach (KeyValuePair sectionValuePair in Sections)
{
streamWriter.WriteLine(string.Concat("[", sectionValuePair.Key, "]"));
foreach (KeyValuePair valuePair in sectionValuePair.Value.Values)
{
if (valuePair.Value != null)
streamWriter.WriteLine(string.Concat(valuePair.Key.Trim(), "=", valuePair.Value.Trim()));
else
streamWriter.WriteLine(valuePair.Key.Trim());
}
streamWriter.WriteLine();
}
}
}
}
///
/// Read an ini-file.
///
/// The name of the file.
public void LoadFromFile(string fileName)
{
Sections.Clear();
using (Stream stream = fileSupport.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader streamReader = new StreamReader(stream))
{
IniFileSection currentSection = null;
while (!streamReader.EndOfStream)
{
string line = streamReader.ReadLine().Trim();
if (!string.IsNullOrEmpty(line))
{
if (line.StartsWith("["))
{
if (line.EndsWith("]"))
{
string sectionName = line.Substring(1, line.Length - 2);
currentSection = new IniFileSection();
Sections[sectionName] = currentSection;
}
else
{
// Bad section name. Ignore this line.
}
}
else if (currentSection != null)
{
int equalSignIndex = line.IndexOf('=');
if (equalSignIndex > -1)
{
string key = line.Substring(0, equalSignIndex);
string value = line.Substring(equalSignIndex + 1);
currentSection.Values[key] = value;
}
else
currentSection.Values[line] = null;
}
else
{
// No section has started. Ignore this line.
}
}
}
}
}
}
}
///
/// A section of an Ini file.
///
public class IniFileSection
{
///
/// Constructor.
///
public IniFileSection()
{
Values = new Dictionary();
}
///
/// The values of the section.
///
public Dictionary Values { get; private set; }
}
}