Reputation: 11592
We are delveloping C# windows based application .net 4 environment.In My application, i want to update settings file(app.config) attribute programatically.Actually we created one user interface(textbox).So, User will enter the new configuration information in the textbox.When clicking the save button, i want to update this value in settings file permanently.
for example:
I have Encryption Key in my settings file.Suppose, user may enter the new encryption key using that interface,then it will automatically update the settings file Encryption key value.
Is this possible?
Upvotes: 1
Views: 2806
Reputation: 89
This may help
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appsettings = (AppSettingsSection)config.GetSection("appSettings");
appsettings.Settings["Key"].Value = "value";
config.Save(ConfigurationSaveMode.Modified);
Upvotes: 0
Reputation: 50672
The best way to edit the app.config is by creating a setup project.
A setup project will run as Admin and will be allowed to write in the program files folder. Writing to the program files folder by regular, standard users is not allowed.
During the setup you could gather information from the users about values that should be set in the config file and you could search for the correct folder.
Note that if you want to change the per user settings you will not run into this issue because the user setting are written in the profile of the user.
Upvotes: 1
Reputation: 25337
Do you want to edit the config file at runtime? This is possible. Use the ConfigurationManager class from the System.Configuration assembly (add reference to it). You an get any section you like e.g. appSettings and modify them.
Upvotes: 0
Reputation: 72636
First of all you have to add this reference : System.Configuration
, then you can write to app.config
for example with this code :
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup applicationSectionGroup = config.GetSectionGroup("applicationSettings");
ConfigurationSection applicationConfigSection = applicationSectionGroup.Sections["YourApp.Properties.Settings"];
ClientSettingsSection clientSection = (ClientSettingsSection)applicationConfigSection;
//Encryption Key Configuration Setting
SettingElement applicationSetting = clientSection.Settings.Get("EncryptionKey");
applicationSetting.Value.ValueXml.InnerXml = this.textBoxKey.Text.Trim();
applicationConfigSection.SectionInformation.ForceSave = true;
config.Save();
ConfigurationManager.RefreshSection("applicationSettings");
Bear in mind that you have to create the app.config file before with the Visual studio wizard, in this example i have called the field for the encryption key : EncryptionKey
and the related textbox in the form : textBoxKey
.
Upvotes: 4