Adding new key/value pairs to appSettings

M

Mark Rae

Hi,

Apologies if this is a stupid question, but it's late...

I have a C# 2 WinForms project called RTES, and I'm trying to add new
key/value pairs to the appSettings section of its config file. I'm using the
code here:
http://www.codeproject.com/useritems/SystemConfiguration.asp?msg=1971660 as
an example.

The folder \RTES\bin\debug folder contains the following files:

RTES.exe
RTES.exe.config
RTES.pdb
RTES.vshost.exe
RTES.vshost.exe.config

When I run the app in debug mode, RTES.vshost.exe.config gets updated with
the new key/value pair - RTES.exe.config doesn't...

However, as soon as I exit the app, RTES.vshost.exe.config reverts to the
way it was...

Is this normal?

Is it not possible to use the AppSettings.Settings.Add(...) method to add
new key/value pairs permanently...?

Any assistance gratefully received.

Mark
 
D

D. Yates

Mark,
However, as soon as I exit the app, RTES.vshost.exe.config reverts to the
way it was...

Is this normal?

I have observed this as well and it is confusing; however, try running the
application directly view windows explorer. The observed behavior is
associated with running the code via Visual Studio. Now, maybe one of the
smart folks that monitor this newsgroup can explain why this happens.

I'm just going to assume that you are calling the Save method on the
configuration instances after you added the new key/value pair.

Dave
 
M

Mark Rae

Dave,
I have observed this as well and it is confusing; however, try running
the application directly view windows explorer. The observed behavior is
associated with running the code via Visual Studio. Now, maybe one of the
smart folks that monitor this newsgroup can explain why this happens.

It was very late, I was very tired, and I had completely forgotten that
VS.NET exhibits this behaviour. Obviously, as soon as ran the compiled .exe,
everything worked as normal.
I'm just going to assume that you are calling the Save method on the
configuration instances after you added the new key/value pair.

:)

Code follows, in case it could be of any use to anybody:

public static bool SaveSetting(string pstrKey, string pstrValue)
{
Configuration objConfigFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
bool blnKeyExists = false;

foreach (string strKey in objConfigFile.AppSettings.Settings.AllKeys)
{
if (strKey == pstrKey)
{
blnKeyExists = true;
objConfigFile.AppSettings.Settings[pstrKey].Value = pstrValue;
break;
}
}
if (!blnKeyExists)
{
objConfigFile.AppSettings.Settings.Add(pstrKey, pstrValue);
}
objConfigFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top