Reputation: 325
I've stepped through my code and all seems to be working. I'm taking two values from an async response and I'm trying to write it to my appSettings
in app.Config
however....when I force refresh of my app.config, there are no values there at all.
Code for getting and writing values to app.config
is
public void Authenticated(Action success, Action<Exception> failure)
{
Client.GetAccessTokenAsync((accessToken) =>
{
UserToken = accessToken.Token;
UserSecret = accessToken.Secret;
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = config.AppSettings.Settings;
if (settings["userLoginSecret"] == null && settings["userLoginToken"] == null)
{
settings.Add("userLoginSecret", UserSecret);
settings.Add("userLoginToken", UserToken);
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
if (success != null) success();
},
(error) =>
{
if (failure != null) failure(error);
});
}
And my app.Config
file is staying like this:
<appSettings>
<add key="userLoginToken" value=""/>
<add key="userLoginSecret" value=""/>
</appSettings>`
Any help much appreciated....
Upvotes: 0
Views: 1436
Reputation: 121
When you are running your application in Visual Studio in debug the configuration file that is actually modified is appname.vshost.exe.config, so be sure to check the correct file.
When you compile the project the file to be modified is instead appname.exe.config and not the app.config inside the source code folder.
If you want to test the normal .exe.config file during Debug you should uncheck the box "Enable the Visual Studio hosting process" in the "Debug" tab of the project properties.
Moreover, if in your app.config file the two keys already exist, with this snippet of code:
if (settings["userLoginSecret"] == null && settings["userLoginToken"] == null)
{
settings.Add("userLoginSecret", UserSecret);
settings.Add("userLoginToken", UserToken);
}
you insert the values only if the condition is satisfied and the keys are not present. If you want to update the values also if they have been already inserted you should add:
else
{
settings["userLoginSecret"].Value = UserSecret;
settings["userLoginToken"].Value = UserToken;
}
Upvotes: 1
Reputation: 1869
Instead of using ConfigurationManager
, consider adding Settings in
Project\Properties\Settings.settings
Make sure the scope of your setting is "User"
Then you can write to the settings via code:
Properties.Settings.Default.SettingName = "Value";
Properties.Settings.Default.Save();
To read the setting:
String value = Properties.Settings.Default.SettingName;
Upvotes: 0