用C#读取ini文件

我正在尝试读取具有以下格式的ini文件:

SETTING=VALUE SETTING2=VALUE2 

我目前有以下代码:

 string cache = sr.ReadToEnd(); string[] splitCache = cache.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries); 

这给了我一个设置列表,但是,我想要做的是把它读成字典。 我的问题是,有没有办法在不迭代整个数组并手动填充字典的情况下执行此操作?

那么,你可以使用LINQ并做

 Dictionary ini = (from entry in splitCache let key = entry.Substring(0, entry.FirstIndexOf("=")) let value = entry.Substring(entry.FirstIndexOf("=")) select new { key, value }).ToDictionary(e => e.key, e => e.value); 

正如Binary Worrier在评论中指出的那样,这种方式与其他答案所建议的简单循环相比没有任何优势。

编辑:上面的块的较短版本将是

 Dictionary ini = splitCache.ToDictionary( entry => entry.Substring(0, entry.FirstIndexOf("="), entry => entry.Substring(entry.FirstIndexOf("=")); 

迭代有什么问题?

 var lines = File.ReadAllLines("pathtoyourfile.ini"); var dict = new Dictionary(); foreach(var s in lines) { var split = s.Split("="); dict.Add(split[0], split[1]); } 

实际上有一个用于在kernel32.dll读/写INI文件的Windows API; 有关示例,请参阅此CodeProject文章 。

INI文件有点棘手,所以我不建议你自己滚动。 我编写了Nini ,它是一个包含非常快速解析器的配置库。

样本INI文件:

 ; This is a comment [My Section] key 1 = value 1 key 2 = value 2 [Pets] dog = rover cat = muffy 

相同的C#代码:

 // Load the file IniDocument doc = new IniDocument ("test.ini"); // Print the data from the keys Console.WriteLine ("Key 1: " + doc.Get ("My Section", "key 1")); Console.WriteLine ("Key 2: " + doc.Get ("Pets", "dog")); // Create a new section doc.SetSection ("Movies"); // Set new values in the section doc.SetKey ("Movies", "horror", "Scream"); doc.SetKey ("Movies", "comedy", "Dumb and Dumber"); // Remove a section or values from a section doc.RemoveSection ("My Section"); doc.RemoveKey ("Pets", "dog"); // Save the changes doc.Save("test.ini"); 

试试这样吧

 [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")] public static extern int GetPrivateProfileString(string SectionName, string KeyName, string Default, StringBuilder Return_StringBuilder_Name, int Size, string FileName); 

并调用这样的函数

 GetPrivateProfileString(Section_Name, "SETTING", "0", StringBuilder_Name, 10, "filename.ini"); 

可以从StringBuilder_Name访问值。

为什么不将文件作为单独的行读取,然后在第一个= ?上拆分它们?

 var dict = new Dictionary(); foreach (var line in File.ReadAllLines(filename)) { var parts = line.Split('=', 2); // Maximum of 2 parts, so '=' in value ignored. dict.Add(parts[0], parts[1]); } 

(在.NET 4中,将ReadAllLines替换为ReadLines ,以避免创建数组, ReadLines返回IEnumerable并懒惰地读取文件。)