Click to See Complete Forum and Search --> : xml configuration file


Sarevok
October 12th, 2005, 10:30 PM
Greetings,


I am currently developing a program that reads parameters from a configuration file. I need the configuration file to be in an xml format but I also need it to be editable by the user. I tried using the App.conf file but found out that it doesn't work when the App.conf file is renamed. Anybody know where to change the settings so that the program will work even if I rename the App.conf file?

Here's the code that I used


using System;
using System.Configuration;
public class Conf
{
public static string GetAppSetting(string key)
{
return (ConfigurationSettings.AppSettings[key] != null)
? ConfigurationSettings.AppSettings[key]
: string.Empty;
}


public static void Main()
{
string name;
string age;
string email;

name = GetAppSetting("name");
age = GetAppSetting("AGE");

Console.WriteLine(name);
Console.WriteLine(age);
Console.ReadLine();
}
}


and this is the App.conf file


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="temp" value="5.0" />
<add key="Name" value="Roland" />
<add key="Age" value="21" />
<add key="Address" value="Cebu" />
<add key="Email" value="me@me.com"/>
</appSettings>
</configuration>


thanks

darwen
October 12th, 2005, 10:59 PM
You could write your own config file, and read/write it using the XmlSerializer class. Or use the XmlWriter/XmlReader classes.

However you will still need a way of telling the system where it is : i.e. a File/Open menu item or something.

It's not good practice to expect users to manually alter the contents of a config file : the setup should be done inside of your application using a form so you have complete control over the format of the file. Users can (and inherently will) make mistakes when editing the file, whereas if you control its writing in code it won't.

Darwen.

Sarevok
October 12th, 2005, 11:12 PM
Thanks darwen :)

But I need the user to change the config file before running the program since this program is gonna be run in the console...

boudino
October 13th, 2005, 02:19 AM
The config file has to be named yourapp.exe.config and has to placed in the folder where your yourapp.exe resides. Than it can be easily used. User can edit this file. But I agree with darwen that it is task only for advanced user.

To app.config - it is only VS hack/feature. If you have app.config file in your project, after compilation VS copies it to output folder under name assembly.exe.config. (And overrides file already existing file).

darwen
October 13th, 2005, 03:06 AM
With console apps you're better off using command line arguments.

Darwen.