This is my code:
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = configuration.AppSettings.Settings;
settings["IP"].Value = "10.0.0.2";
configuration.Save(ConfigurationSaveMode.Modified);
when I break on settings["IP"].Value line, i get the correct value.
The method completes without any errors but app.config file remains unchanged.
This code should work:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["IP"].Value = "10.0.0.2";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
As per my knowledge you can't persist the updated value in App.config.
If you want to persist the config value,do the normal XML operation.
Related
My requirement is to update the appsettings file at run time when the application is started. But encountered with a problem where web config is getting replaced every minute with the new appsettings. How can I stop replacing every minute?
I have gone through different solutions here and implemented as below:
In web config we have default path for appsettings:
appSettings file="C:\Config\MyProj\Appsettings.Config"
In the Global.asax.cs, I am calling the following method to replace the my appsettings file dynamically.
public void ChangeAppSettings(string path)
{
System.Configuration.Configuration configuration = null;
if (System.Web.HttpContext.Current != null)
{
configuration =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
configuration =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
// update appconfig file path
configuration.AppSettings.File = path;
// Save the configuration file.
configuration.Save(ConfigurationSaveMode.Modified);
// Force a reload in memory of the changed section.
ConfigurationManager.RefreshSection("appSettings");
}
Or is there a better way to implement?
Following code did the trick, for somereason every time we refresh the config ChangeAppSettings method is called. So I just added to check if the config is already modified then don't refresh anymore.
if (!path.Equals(configuration.AppSettings.File))
{
// update appconfig file path
configuration.AppSettings.File = path;
// Save the configuration file.
configuration.Save(ConfigurationSaveMode.Modified);
// Force a reload in memory of the changed section.
ConfigurationManager.RefreshSection("appSettings");
}
I have a WinForms .exe with an App.config that has a bunch of User Scoped Settings that are set at runtime and saved.
I want to be able to use the WinForms app to change and save the settings and then click on button to do some work based on the those settings.
I also want to read the user settings in the same .config file from a sep. console app so I can schedule to work to be done as a scheduled task.
What is the best way to be able to do this?
Update:
I tried the reccommendation of using ConfigurationManager.OpenExeConfiguration as described in some of the answers like so.
Configuration config = ConfigurationManager.OpenExeConfiguration("F:\\Dir\\App.exe");
but when I try to retrieve a User Setting like so.
string result = config.AppSettings.Settings["DB"].ToString();
I get a Null reference error.
From code in the exe however the following correctly returns the DB name.
Properties.Settings.Default.DB
Where am I going wrong?
Update 2:
So based on some of the answers below I now can use the following to retrieve the raw XML of the section of the user.config file I am interested in from sep. ConsoleApp.
System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"D:\PathHere\user.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);
System.Configuration.DefaultSection configSection = (System.Configuration.DefaultSection)config.GetSection("userSettings");
string result = configSection.SectionInformation.GetRawXml();
Console.WriteLine(result);
But I am still unable to just pull the value for the specific element I am interested in.
this should do it :
var clientSettingsSection = (System.Configuration.ClientSettingsSection)(ConfigurationManager.GetSection("userSettings/YourApplicationName.Properties.Settings"));
var setting = clientSettingsSection.Settings.Get("yourParamName_DB_");
string yourParamName_DB = ((setting.Value.ValueXml).LastChild).InnerText.ToString();
You can use the ConfigurationManager class to open the configuration file of another executable.
Configuration conf = ConfigurationManager.OpenExeConfiguration(exeFilePath);
// edit configuration settings
conf.Save();
See ConfigurationManager.OpenExeConfiguration
If you are setting these values per user basis you may need to use the ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel) method instead of the current method you are using now.
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Environment.CurrentDirectory + "\\MyApp.exe.config";
//i have config in the same directory as my another app
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var settingsSection = (System.Configuration.ClientSettingsSection)config.GetSection("userSettings/MyApp.Properties.Settings");
var setting = settingsSection.Settings.Get("MySetting");
var param = ((setting.Value.ValueXml).LastChild).InnerText.ToString();
If you know the path to the config file try:
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration("configPath");
string myValue = config.AppSettings.Settings[ "myValue" ].Value;
I have a Windows Service written, and want to modify it's config file. I have an app in the same solution for this:
private ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = #"pathToMyWSConfigFile";
and then I do:
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("ServerPath", "test replace ");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
However this simply adds another value to the ServerPath key in config file, and I want to replace it, so that there is always only one value there. How can I do it?
To update a setting, simply use the Settings indexer.
config.AppSettings.Settings["ServerPath"].Value = "test replace";
I'm struggling with trying to modify the appSettings part of the app.config file of my application. However I'm not receiving any error/exception and I can read values without any problem.
Here is how I tried to set values :
ConfigurationManager.AppSettings.Set("DaysLeft", Days.Text.ToString());
//
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["DaysLeft"].Value = Days.Text.ToString();
//when I debug the app, I notice that the value is changed in the previous line
The app.config file isn't being modified.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["DaysLeft"].Value = Days.Text.ToString();
config.Save();
You need to save your changes
config.Save(ConfigurationSaveMode.Modified);
Also, if you want to reload the app.config
ConfigurationManager.RefreshSection("appSettings");
Good day! I would like to ask, if you know how to modify the web.config.. Its located in a different folder.. I tried using this approach, Unfortunately i doesn't work..
// set Path to your config file
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(sWebConfig);
// open web.config
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
// display message
Console.WriteLine("Updating wizardConnection string.. Please wait for a few minutes..");
// fetch WizardConnection database connection string
var Wizardsection = (ConnectionStringsSection)configuration.GetSection("WizardConnection");
// assign new value to wizardConnection.. Please make sure you have the correct database server. Just update server location, if need
Wizardsection.ConnectionStrings["WizardConnection"].ConnectionString = string.Format(#"server={0};database={1};integrated security=SSPI", sDatabaseServer, sDatabase);
configuration.Save();
Hope to hear from you soon..
Regards,
Link
Instead of updating web.config, you may use different web.config files for different build configurations. For instance, you may setup a new build configuration namely "Staging" and configure it to use a modified config file.
Have a look at Web.Config transformation
Actually what you are doing will change the config file which is copied to folder that contains binary(debug, release or any custom compiler configuration). That is sufficient to change the connection settings of the application. But, if you want to modify the web.config file, it will be nothing but modifying an external file, for which you will need File opertaions.
You should use webconfigurationmanager to open your webconfig.
Try this
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
config.ConnectionStrings.ConnectionStrings["ConnectString"].ConnectionString = string.Format(#"server={0};database={1};integrated security=SSPI", sDatabaseServer, sDatabase);
config.Save();