.NET 2.0 modifying content of app.config file (C#)

Before you start, make sure you have added reference to System.Configuration.dll for .NET 2.0. I think the default the Visual Studio C# Express referenced to is from .NET 1.1 which will not compile.

using System.Configuration;
using System.Collections.Specialized;

//to write
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Remove("myKey");
config.AppSettings.Settings.Add("myKey", "123");

config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");

//to read
NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings;
string strRead = (string)appSettings["myKey"];


Content of app.config

<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings>
<add key="myKey" value = "123"/>
</appSettings> </configuration>

Comments

Unknown said…
Your post wont change anything in The configuration file
Anthony Yio said…
Refering MSDN

To get the Configuration object for a resource, your code must have read permissions on all the configuration files from which it inherits settings. To update a configuration file, your code must additionally have write permissions for both the configuration file and the directory in which it exists.

More info from MSDN

Specify which configuration to get by passing one of the following values for userLevel:

To get the Configuration object that applies to all users, set userLevel to None.

To get the local Configuration object that applies to the current user, set userLevel to PerUserRoamingAndLocal.

To get the roaming Configuration object that applies to the current user, set userLevel to PerUserRoaming.
Unknown said…
during debug mode, it modified the myApp.vshost.exe.config as expected but as soon as you exit, all changes are gone.

I tired other options like PerUserRoamingAndLocal, I can't save it and got exception. seems like the path is set to

C:\\Documents and Settings\\mylogin\\Local Settings\\Application Data\\CompanyName,\\myApp.vshost.exe_Url_mbfzze1fclzcbo4e1lznw2zkzd5ygpym\\1.0.0.0\\user.config

but the path does not exist. I don't think I should manually create this path, right?

Popular posts from this blog

Outlook : "operation failed, object could not be found. " when trying to close a PST.

How to transfer app and data from old iPhone to new iPhone for model IOS17 and IOS18 above.

Troubleshooting Outlook Express (IMAP, POP3, HTTP, NEWS) with the log file