Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class INIFile
- {
- public IDictionary<string, IDictionary<string, string>> list = new Dictionary<string, IDictionary<string, string>>();
- public string iniPath;
- public INIFile(string iniPath)
- {
- this.iniPath = iniPath;
- string text = File.ReadAllText(iniPath);
- string pattern = @"
- ^
- ((?:\[)
- (?<Section>[^\]]*)
- (?:\])
- (?:[\r\n]{0,}|\Z))
- (
- (?!\[)
- (?<Key>[^=\s*]*)
- (?:\s*=\s*)
- (?<Value>[^\r\n]*)
- (?:\s*[\r\n]{0,})
- )+";
- var matches = Regex.Matches(text, pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
- foreach (Match property in matches)
- {
- var dic = new Dictionary<string, string>();
- int max = property.Groups["Key"].Captures.Count;
- for (int i = 0; i < max; i++)
- dic.Add(property.Groups["Key"].Captures[i].Value, property.Groups["Value"].Captures[i].Value);
- list.Add(property.Groups["Section"].Value, dic);
- }
- }
- public INIFile()
- {
- }
- public string this[string key, string key2]
- {
- get
- {
- foreach (string x in list.Keys)
- {
- if (x.Equals(key, StringComparison.OrdinalIgnoreCase))
- {
- foreach (string z in list[x].Keys)
- {
- if (z.Equals(key2, StringComparison.OrdinalIgnoreCase))
- {
- return list[x][z];
- }
- }
- return "!Key:" + key2 + " in:"+x +" doesnt exist!";
- }
- }
- return "!Key:"+key+" doesnt exist!";
- }
- set
- {
- foreach (string x in list.Keys)
- {
- if (x.Equals(key, StringComparison.OrdinalIgnoreCase))
- {
- foreach (string z in list[x].Keys)
- {
- if (z.Equals(key2, StringComparison.OrdinalIgnoreCase))
- {
- list[x][z] = value;
- return;
- }
- }
- list[x].Add(key2, value);
- return;
- }
- }
- list.Add(key, new Dictionary<string, string>());
- list[key].Add(key2, value);
- }
- }
- public void Save(string path)
- {
- StringBuilder builder = new StringBuilder();
- foreach (var x in list)
- {
- builder.Append("[");
- builder.Append(x.Key);
- builder.Append("]\r\n");
- foreach (var z in x.Value)
- {
- builder.Append(z.Key);
- builder.Append(" = ");
- builder.Append(z.Value);
- builder.Append("\r\n");
- }
- builder.Append("\r\n");
- }
- File.WriteAllText(path, builder.ToString());
- }
- public void Save()
- {
- if (iniPath == null || iniPath == "")
- throw new Exception("Cant save file, please use the other method or declare iniPath");
- Save(iniPath);
- }
- }
Add Comment
Please, Sign In to add comment