在C#中读取ini文件 [英] Reading ini file in C#
问题描述
我想读一个具有以下格式的INI文件:
I am trying to read an ini file that has the following format:
SETTING=VALUE
SETTING2=VALUE2
目前,我有以下的code:
I currently have the following code:
string cache = sr.ReadToEnd();
string[] splitCache = cache.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
这给了我的设置列表,但是,我想要做的读入字典这一点。我的问题是,有没有办法做到这一点,而无需通过整个数组遍历并手动填充字典?
Which gives me a list of settings, however, what I would like to do is read this into a dictionary. My question is, is there a way to do this without iterating through the entire array and manually populating the dictionary?
推荐答案
好了,你可以使用LINQ和做
Well, you could use LINQ and do
Dictionary<string, string> 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);
作为二进制杞人忧天在评论中指出,这样做的这种方式拥有了其他的答案提出的简单循环没有优势。
As Binary Worrier points out in the comments, this way of doing this has no advantages over the simple loop suggested by the other answers.
编辑:块的一个较短的版本上面会
A shorter version of the block above would be
Dictionary<string, string> ini = splitCache.ToDictionary(
entry => entry.Substring(0, entry.FirstIndexOf("="),
entry => entry.Substring(entry.FirstIndexOf("="));
这篇关于在C#中读取ini文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!