tags:

views:

2286

answers:

4

My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.

I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.

I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?

MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format.
string Value1 = kv.get("Key1");
...
+3  A: 

I don't know of any builtin class to parse ini file. I've used nini when needed to do so. It's licensed under the MIT/X11 license, so doesn't have any issue to be included in a closed source program.

It's very to use. So if you have a Settings.ini file formatted this way:

[Configuration]
Name = Jb Evain
Phone = +330101010101

Using it would be as simple as:

var source = new IniConfigSource ("Settings.ini");
var config = source.Configs ["Configuration"];

string name = config.Get ("Name");
string phone = config.Get ("Phone");
Jb Evain
A: 

Format the file this way:

key1=value1 key2=value2

Read the entire file into a string (there is a simple convenience function that does that, maybe in the File or string class), and call string.Split('='). Make sure you also call string.Trim() on each key and value as you traverse the list and pop each pair into a hashtable or dictionary.

Jeff Kotula
+3  A: 

Use the KeyValuePair class for you Key and Value, then just serialize a List to disk with an XMLSerializer.

That would be the simplest approach I feel. You wouldn't have to worry about traversing nodes. Calling the Deserialize function will do that for you. The user could edit the values in the file if they wish also.

Nicholas Mancuso
One has to take into account that `KeyValuePair` is not serializable. More detailled description of the solution here is discussed in this follow-up question: http://stackoverflow.com/questions/2658916/serializing-a-list-of-key-value-pairs-to-xml
Slauma
A: 

if you want the user to be able to read and modify the file, i suggest a comma-delimited pair, one per line

key1,value1
key2,value2
...

parsing is simple: read the file, split at newline or comma, then take the elements in pairs

Steven A. Lowe
Might as well make it equivalent in format to a Java Properties file and use equals instead of comma.
JeeBee
@JeeBee: but that would assume that the user would be familiar with a java properties file format; a csv format can be edited with Excel or notepad
Steven A. Lowe