你的位置:首页 > ASP.net教程

[ASP.net教程][C#]INI文件控制类


INI文件常用于保存各类设置或本地化文本,大概格式如下:

[Section]key=value

然而.NET框架似乎并没有提供一个实用的工具来操作它,或许是因为MS想让我们都使用Settings类控制的config文件?
但是出于多种原因,我还是不太喜欢用Settings类以及这个

幸运的是,有两个Win32API可以帮我们完成INI文件的控制:
WritePrivateProfileString
GetPrivateProfileString

但是非常尴尬的是这俩一个能写入中文,另一个却读不好中文。。。

于是只好自己动手丰衣足食了,谨记于此以备日后又有所需:

 1 abstract class ConfigurationBase 2 { 3   public abstract string Path { get; } 4  5   public abstract string Section { get; } 6  7   /// <summary> 8   /// 指定好编码格式就能支持各种语言文字了 9   /// </summary> 10   private readonly Encoding encoding = Encoding.UTF8; 11  12   public void Clear() 13   { 14     File.Delete(Path); 15   } 16  17   public void Save() 18   { 19     File.WriteAllLines(Path, lines.ToArray(), encoding); 20   } 21  22   private readonly List<string> lines; 23  24   protected ConfigurationBase() 25   { 26     if (File.Exists(Path)) 27     { 28       lines = new List<string>( 29         File.ReadAllLines(Path, encoding)); 30     } 31     else 32     { 33       lines = new List<string>(); 34     } 35   } 36  37   protected string Get(string key, string defaultVal) 38   { 39     if (lines.Count != 0) 40     { 41       string sectionLine = String.Format("[{0}]", Section); 42       string keyLine = String.Format("{0}=", key); 43       Regex otherSection = new Regex(@"^\[[^\]+]\]$", RegexOptions.Compiled); 44  45       bool inSection = false; 46       foreach (string line in lines) 47       { 48         if (sectionLine == line) 49         { 50           inSection = true; 51         } 52         else if (otherSection.IsMatch(line)) 53         { 54           if (inSection) break; 55         } 56         else if (inSection && line.StartsWith(keyLine)) 57         { 58           return line.Substring(keyLine.Length); 59         } 60       } 61     } 62     return defaultVal; 63   } 64  65   protected void Set(string key, string value) 66   { 67     string sectionLine = String.Format("[{0}]", Section); 68     string keyLine = String.Format("{0}=", key); 69     Regex otherSection = new Regex(@"^\[[^\]+]\]$", RegexOptions.Compiled); 70     string valueLine = String.Format("{0}{1}", keyLine, value); 71  72     bool inSection = false; 73     for (int i = 0; i < lines.Count; i++) 74     { 75       if (sectionLine == lines[i]) 76       { 77         inSection = true; 78       } 79       else if (otherSection.IsMatch(lines[i])) 80       { 81         if (inSection) 82         { 83           lines.Insert(i, valueLine); 84           break; 85         } 86       } 87       else if (inSection && lines[i].StartsWith(keyLine)) 88       { 89         lines[i] = valueLine; 90       } 91     } 92     if (inSection) 93     { 94       lines.Add(valueLine); 95     } 96     else 97     { 98       lines.Add(sectionLine); 99       lines.Add(valueLine);100     }101   }102 }