Tuesday, April 10, 2007

Long time, tied up with some work... but i am going to keep this rolling.
Let's take a light topic... do you know how to Read and write web App.config files?
Here it is...
Read Config -
static void ReadConfig()
foreach(string key in ConfigurationManager.AppSettings)
{ string value = ConfigurationManager.AppSettings[key];
Console.WriteLine("Key: {0}, Value: {1}", key, value);

Write Config -
static void WriteConfig() {
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// Add an Application Setting.
config.AppSettings.Settings.Add("ModifiedDate", DateTime.Now.ToLongTimeString() + " ");
// Save the changes in App.config file.
// Force a reload of a changed section.

Key: Settings1, Value: Value1
Key: Modified Date, Value: 12:00:00

Ok, did you figure that the app.config does not stick values for the keys that you added or for the keys that you modified. Check the app.exe.config in the debug or release version. You should find it stick there. I foudn it little wierd but not sure when in debug mode i could not find app.config modified but had app.exe.config modified. If anyone you have had the same experience and seems that i might have missed something then please let me know.

Well, before i end you have another option as Settings file that can be used to get/set settings at user/application level for your application as well.

Thanks - Dipesh

No comments: