Click to See Complete Forum and Search --> : Reading a properties file


tomtom1923
March 1st, 2010, 10:19 AM
I am looking for a better method to read a properties file. My program loads and does a loop with some processing based on a properties file. The properties file can be changed on the fly to change how the loop runs or what processing is performed.

Here is what I do right now:

The config file has values like this:

source=c:\data\data.txt

string[] configProp = File.ReadAllLines(@"config.properties");

I load the file into a string array. I then proceed to reassign string array value into a new string and perform trims to remove the leader "source=" and I am left with "c:\data\data.txt" which is my usable variable.

This just seems like a lot of extra work, does anyone know of a better way to load a properties file?

rliq
March 1st, 2010, 07:27 PM
Try this:

IEnumerable<KeyValuePair<String, String>> properties = from p in File.ReadAllLines(@"config.properties")
select new KeyValuePair<String, String>(
p.Split(new Char[] { '=' })[0],
p.Split(new Char[] { '=' })[1]);

foreach(KeyValuePair<String, String> property in properties)
{
...
}

boudino
March 2nd, 2010, 01:39 AM
Is properties file a must, or can you use other format, e.g. .NET"s common config file? If so, there are plenty classes in System.Configuration namespace which can help you.