Guest User

Untitled

a guest
Jul 17th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.81 KB | None | 0 0
  1. public class INIFile
  2. {
  3. public IDictionary<string, IDictionary<string, string>> list = new Dictionary<string, IDictionary<string, string>>();
  4. public string iniPath;
  5.  
  6. public INIFile(string iniPath)
  7. {
  8. this.iniPath = iniPath;
  9. string text = File.ReadAllText(iniPath);
  10. string pattern = @"
  11. ^
  12. ((?:\[)
  13. (?<Section>[^\]]*)
  14. (?:\])
  15. (?:[\r\n]{0,}|\Z))
  16. (
  17. (?!\[)
  18. (?<Key>[^=\s*]*)
  19. (?:\s*=\s*)
  20. (?<Value>[^\r\n]*)
  21. (?:\s*[\r\n]{0,})
  22. )+";
  23.  
  24. var matches = Regex.Matches(text, pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
  25. foreach (Match property in matches)
  26. {
  27. var dic = new Dictionary<string, string>();
  28. int max = property.Groups["Key"].Captures.Count;
  29. for (int i = 0; i < max; i++)
  30. dic.Add(property.Groups["Key"].Captures[i].Value, property.Groups["Value"].Captures[i].Value);
  31. list.Add(property.Groups["Section"].Value, dic);
  32. }
  33. }
  34.  
  35. public INIFile()
  36. {
  37.  
  38. }
  39.  
  40. public string this[string key, string key2]
  41. {
  42. get
  43. {
  44. foreach (string x in list.Keys)
  45. {
  46. if (x.Equals(key, StringComparison.OrdinalIgnoreCase))
  47. {
  48. foreach (string z in list[x].Keys)
  49. {
  50. if (z.Equals(key2, StringComparison.OrdinalIgnoreCase))
  51. {
  52. return list[x][z];
  53. }
  54. }
  55. return "!Key:" + key2 + " in:"+x +" doesnt exist!";
  56. }
  57. }
  58. return "!Key:"+key+" doesnt exist!";
  59. }
  60. set
  61. {
  62. foreach (string x in list.Keys)
  63. {
  64. if (x.Equals(key, StringComparison.OrdinalIgnoreCase))
  65. {
  66. foreach (string z in list[x].Keys)
  67. {
  68. if (z.Equals(key2, StringComparison.OrdinalIgnoreCase))
  69. {
  70. list[x][z] = value;
  71. return;
  72. }
  73. }
  74. list[x].Add(key2, value);
  75. return;
  76. }
  77. }
  78. list.Add(key, new Dictionary<string, string>());
  79. list[key].Add(key2, value);
  80. }
  81. }
  82.  
  83. public void Save(string path)
  84. {
  85. StringBuilder builder = new StringBuilder();
  86. foreach (var x in list)
  87. {
  88. builder.Append("[");
  89. builder.Append(x.Key);
  90. builder.Append("]\r\n");
  91. foreach (var z in x.Value)
  92. {
  93. builder.Append(z.Key);
  94. builder.Append(" = ");
  95. builder.Append(z.Value);
  96. builder.Append("\r\n");
  97. }
  98. builder.Append("\r\n");
  99. }
  100. File.WriteAllText(path, builder.ToString());
  101. }
  102.  
  103. public void Save()
  104. {
  105. if (iniPath == null || iniPath == "")
  106. throw new Exception("Cant save file, please use the other method or declare iniPath");
  107. Save(iniPath);
  108. }
  109. }
Add Comment
Please, Sign In to add comment