Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading ini file in C#

Tags:

arrays

string

c#

I am trying to read an ini file that has the following format:

SETTING=VALUE 
SETTING2=VALUE2

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?

like image 737
Paul Michaels Avatar asked Dec 01 '22 05:12

Paul Michaels


1 Answers

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.

Edit: 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("="));
like image 80
Jens Avatar answered Dec 04 '22 08:12

Jens