Change Default App.Config At Runtime

Change default app.config at runtime

The hack in the linked question works if it is used before the configuration system is used the first time. After that, it doesn't work any more.

The reason:

There exists a class ClientConfigPaths that caches the paths. So, even after changing the path with SetData, it is not re-read, because there already exist cached values. The solution is to remove these, too:

using System;
using System.Configuration;
using System.Linq;
using System.Reflection;

public abstract class AppConfig : IDisposable
{
public static AppConfig Change(string path)
{
return new ChangeAppConfig(path);
}

public abstract void Dispose();

private class ChangeAppConfig : AppConfig
{
private readonly string oldConfig =
AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();

private bool disposedValue;

public ChangeAppConfig(string path)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
ResetConfigMechanism();
}

public override void Dispose()
{
if (!disposedValue)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig);
ResetConfigMechanism();


disposedValue = true;
}
GC.SuppressFinalize(this);
}

private static void ResetConfigMechanism()
{
typeof(ConfigurationManager)
.GetField("s_initState", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, 0);

typeof(ConfigurationManager)
.GetField("s_configSystem", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);

typeof(ConfigurationManager)
.Assembly.GetTypes()
.Where(x => x.FullName ==
"System.Configuration.ClientConfigPaths")
.First()
.GetField("s_current", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
}
}
}

Usage is like this:

// the default app.config is used.
using(AppConfig.Change(tempFileName))
{
// the app.config in tempFileName is used
}
// the default app.config is used.

If you want to change the used app.config for the whole runtime of your application, simply put AppConfig.Change(tempFileName) without the using somewhere at the start of your application.

Change app.config programmatically at the runtime

Because you are using a custom section you need to do it with:

var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var path = @"//oracle.manageddataaccess.client/version/settings/setting[@name='TNS_ADMIN']";
var attrs = xmlDoc.SelectSingleNode(path).Attributes["value"].Value = "some value";
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection(path);

This should work in case of default appSettings section:

System.Configuration.Configuration cnf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cnf.AppSettings.Settings["TNS_ADMIN"].Value = "my value";
cnf.Save(ConfigurationSaveMode.Modified);

Documentation

Changing App.config at Runtime

UPDATE

The solution below did not work because XmlDocument does not dispose and it seems some versions of .net do not close correctly when given a file path. The solution (example code in the link) is to open a stream which will do a dispose and pass that stream to the save function.

A solution is shown here. http://web-beta.archive.org/web/20150107004558/www.devnewsgroups.net/group/microsoft.public.dotnet.xml/topic40736.aspx


Old stuff below

Try this:

Note, I changed to xpath, but it has been a while so I might have gotten the xpath wrong, but in any case you should use xpath and not walk the tree. As you can see it is much clearer.

The important point is the using statement which will dispose(), which I think was your problem.

Let me know, good luck.

  public void UpdateAppSettings(string key, string value)
{
using (XmlDocument xmlDoc = new XmlDocument())
{
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
xmlDoc.DocumentElement.FirstChild.SelectSingleNode("descendant::"+key).Attributes[0].Value = value;
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
System.Configuration.ConfigurationManager.RefreshSection("section/subSection");
}

How do I modify config file at runtime

It's definitely possible, I did this at work a while back. Essentially, you can load a new app.config file into memory, then tell .NET to use the new file. From that point on, all variables in the Configurarion section change when read using the standard .NET calls.

Sorry I cant give specifics, you might have to Google some more - but at least you know its possible!!

Having said this, I believe this is the wrong architectural path to go down. Far better to store your settings in an external file in your own format. It really is a royal pain to update app.config, and if we hadnt had to do it for compatibility reasons with legacy assemblies it would not have been worth it in the least. The legacy assemblies used WCF which in itself was a mistake. WCF is a ghastly architectural morass, with few redeeming features compared to any of the modern alternatives.

Update

  • See Overriding App.Config settings.
  • See Change default app.config at runtime.

Replacing app.config at runtime

Changing the app configuration file must be done before your application starts, as certain keys are read by the runtime when your application is being bootstrapped only, and others are turned into readonly.

You can dynamically change the configuration entries of the AppSettings section only by referencing the System.Configuration assembly. All the other keys are by design read only.

If you don't want to alter the configuration before starting the application, you need to think about all the involved entities: who is going to read your connection string? If it is you, you can simply store it somewhere else or even in the AppSettings key. Instead, if external components require to read it from your configuration file, you have no chance that changing the architecture of your application in order to have a wrapper that does the changes before running your application.

The AppSettings key ca be changed in this way, after refencing the System.Configuration assembly (this is vital).

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="key1" value="configuration"/>
</appSettings>
</configuration>

Program.cs

using System;
using System.Configuration;

namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
System.Configuration.ConfigurationManager.AppSettings["key1"] = "changed";

var value = System.Configuration.ConfigurationManager.AppSettings["key1"];

Console.WriteLine($"This is the new key: {value}.");
}
}
}

Change App.Config file at Runtime Not Worked for users without Administrator rights


exePath = Path.Combine( exePath, "MyApp.exe" );
Configuration config = ConfigurationManager.OpenExeConfiguration( exePath );
var setting = config.AppSettings.Settings[SettingKey];
if (setting != null)
{
setting.Value = newValue;
}
else
{
config.AppSettings.Settings.Add( SettingKey, newValue);
}

config.Save();

Source
https://stackoverflow.com/a/3678953/3156647



Related Topics



Leave a reply



Submit