IniConfig.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. /*
  7. Taken from public code listing at by Alex Pinsker
  8. http://alexpinsker.blogspot.com/2005/12/reading-ini-file-from-c_113432097333021549.html
  9. */
  10. namespace OpenGrid.Framework.Data
  11. {
  12. /// <summary>
  13. /// Parse settings from ini-like files
  14. /// </summary>
  15. public class IniFile
  16. {
  17. static IniFile()
  18. {
  19. _iniKeyValuePatternRegex = new Regex(
  20. @"((\s)*(?<Key>([^\=^\s^\n]+))[\s^\n]*
  21. # key part (surrounding whitespace stripped)
  22. \=
  23. (\s)*(?<Value>([^\n^\s]+(\n){0,1})))
  24. # value part (surrounding whitespace stripped)
  25. ",
  26. RegexOptions.IgnorePatternWhitespace |
  27. RegexOptions.Compiled |
  28. RegexOptions.CultureInvariant);
  29. }
  30. static private Regex _iniKeyValuePatternRegex;
  31. public IniFile(string iniFileName)
  32. {
  33. _iniFileName = iniFileName;
  34. }
  35. public string ParseFileReadValue(string key)
  36. {
  37. using (StreamReader reader =
  38. new StreamReader(_iniFileName))
  39. {
  40. do
  41. {
  42. string line = reader.ReadLine();
  43. Match match =
  44. _iniKeyValuePatternRegex.Match(line);
  45. if (match.Success)
  46. {
  47. string currentKey =
  48. match.Groups["Key"].Value as string;
  49. if (currentKey != null &&
  50. currentKey.Trim().CompareTo(key) == 0)
  51. {
  52. string value =
  53. match.Groups["Value"].Value as string;
  54. return value;
  55. }
  56. }
  57. }
  58. while (reader.Peek() != -1);
  59. }
  60. return null;
  61. }
  62. public string IniFileName
  63. {
  64. get { return _iniFileName; }
  65. } private string _iniFileName;
  66. }
  67. }