I'm trying to change in runtime one key of my applications settings file, but it does not work.
I do on that way:
ConfigurationSettings.AppSettings["XPTO"] = "HELLO";
It seems that it only changes in memory, not on the file.
Does anyone knows how to do this?
Thanks.
Take a look at my overview of .NET settings files...In short, I think you want a user-scoped setting. It will behave more like you expect.
Edit: If you are using the settings designer in Visual Studio, then simply change the "Scope" to "User". If not, you should be able to do the equivalent programmatically.
Assuming your app has write permissions on the file...
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // the config that applies to all users
AppSettingsSection appSettings = config.AppSettings;
if (appSettings.IsReadOnly() == false)
{
appSettings("Key").Value = "new value";
config.Save();
}
I'm ignoring all the possible exceptions that can be thrown...
The AppSettings file is not designed to be writable. It is designed to store configurations that will not change at run time but might change over time ie: DB Connection Strings, web service URL's, etc.
So, while it may be possible to update the file in reality you should re-asses if this value should be stored there.
Related
I have a Full trust, online only, click-once application that relies on settings in the App.config --> appSettings collection.
Once published, the first time the application is executed, the settings are read and everything works fine. If I close the application and run it again, the items that are in appSettings are no longer there and appSettings.Count is equal to 0.
I have set the app.config as "Content" and to "Copy Always".
Any Idea what could be causing the items in appSettings to disappear? or a way to get around this?
Also, please note that the settings are only being read, and being used to determine how the application is run. We're not trying to manipulate the settings.
I guess you are using the settings wrong.
First of all, you need to mind the difference between application and user settings. Application settings are constant and can not be changed from your code (for example default values, connection strings, etc.). User settings are for settings that change when the application runs, usually because there is some sort of Settings dialog in your application.
Secondly, you need to access them properly. People tend to (and I don't know why) use things like ConfigurationManager or other stuff to access settings. It is far easier and less error-prone to use Properties.Settings.Default.SettingName for both application and user settings.
Changing a user setting would read like this:
Properties.Settings.Default.SettingName = settingValue;
Properties.Settings.Default.Save();
The call to Save is important, as otherwise the change will not be persisted.
Thirdly: No need to change the way app.config is included in your project. By default it will be renamed to applicationname.exe.config and will always be included in your output unless you say otherwise. The same goes for the ClickOnce installation: It will be included by default. You may actually break things if you play with this or the ClickOnce deployment settings for app.config! Revert them to default and leave them alone.
Now one case where the settings will be lost and reverted to defaults is when you update your application. In this case you will have to migrate your settings from the previously installed version, otherwise the user settings will be overridden with the default values from the installation. What you do to migrate the settings is:
Define a user setting named SettingsUpgradeRequired (name doesn't really matter - should be self-explaining, however) with a default value of true in the settings designer. Then, when your application starts, you do this:
if (Properties.Settings.Default.SettingsUpgradeRequired)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.SettingsUpgradeRequired = false;
Properties.Settings.Default.Save();
}
This makes sure a migration of the settings only occurs when required. SettingsUpgradeRequired will only be true upon the first installation (in which case Upgrade does nothing) and after an update of your application, because - as I said - by default the configuration from the ClickOnce installation will override the previous configuration until you perform the upgrade.
I've seen this solution proposed, but doesn't seem to work for me:
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
oConfig.AppSettings.Settings["PreferenceToRemember"].Value = “NewValue”;
oConfig.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
It successfully changes the value in memory, but does not save it back to the config file.
I'm trying to do this in a Wpf app, if that makes any difference.
Or is there a preferred way to save user settings to a file?
If your app is installed in \Program Files\ then it may not have permissions to write to the file. Generally, app.config files are modified by hand (in my experience, at least). If you want to persist user preferences, you should look into a .settings file as these are created in the %appdata% (or %localappdata%) directory, which is under the user's directory.
My guess is that using OpenExeConfiguration does not actually open the associated file. For example, you could be running from a XAP, where there would still be a .exe.config inside the .xap, but it doesn't map to an actual file on the filesystem.
You could probably check this by seeing if oConfig.HasFile is true or not.
If my guess is correct, then you'll need to use the OpenExeConfiguration(string) overload; the sample on the MSDN page has a reasonable way to get the right filename, although my first instinct was instead to try System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.
I want to add new settings to the user.config at runtime for a C# application (WPF).
These settings will be added by independent modules so I have no idea what they will be in advance.
Most examples refer to:
Configuration config =
configurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
But this only allows you to access the Application Settings
and you can't save it anyway as it's not meant to be modified.
I want to be able to do something like
Settings.Default.Add("SomeKey", "someobject");
Settings.Default.Save()
after which this setting would be available the next time this specific user
starts the application.
You may wish to check this solution.
It is doable but it is lots of code.
I'm using C# .NET 2.0 Windows Application.
and I'm using app.config for my Application Settings.
but change in AppSettings doesn't reflected runtime, it Needs Application to be restarted.
How can I avoid it.
Here is my code snippet I used to read and write the Application Settings.
I'm reading the Setting like this
string temp = ConfigurationManager.AppSettings.Get(key);
I'm updating the value like this where node is the current configuration/appSettings Node
node.Attributes["value"].Value = value;
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
You could try calling ConfigurationManager.RefreshSection("appSettings") to refresh the AppSettings section of the file from disk. Once they have been refreshed, you should be able to read the new values.
I've just tested this and it does indeed work.
Alternatively, you could create a singleton 'Options' to hold on to your application settings and perform your read/writes for you. Once loaded, changing the .config doesn't require reloading, you simply set a property on the singleton and call your .Save() method.
The 'runtime' version of your settings is in the singleton, no need to read from disk.
Dont use ConfigurationManager to read settings, instead use:
System.Configuration.ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).AppSettings.Settings["value"];
ConfigurationManager.RefreshSection("appSettings");
works!!
But be careful that if we are in debug mode, the configuration file can be called xxxxx.vshost.exe.config, where xxxxx is your project name.
I know it is a good idea to store configuration data in app.config (e.g. database connection strings) instead of hardcoing it, even if I am writing an application just for myself. But is there a way to update the configuration data stored in app.config from the program that is using it?
If you use the Settings for the project, you can mark each setting as either application or user.
If they're set as user, they will be stored per-user and when you call the Save method it will be updated in the config for that user.
Code project has a really detailed article on saving all types of settings.
app.config isn't what you want to use for user-tweakable data, as it'll be stored somewhere in Program Files (which the user shouldn't have write permissions to). Instead, settings marked with a UserScopedSettingAttribute will end up in a user-scoped .config file somewhere in %LocalAppData%.
I found the best way to learn this stuff was to mess with the Visual Studio "Settings" tab (on your project's property pages), then look at the code that it generates and look in %LocalAppData% to see the file that it generates.