在运行时以编程方式更改app.config

时间:2018-11-16 21:30:00

标签: c# .net app-config

我想在运行时动态更改appconfig中的TNS_ADMIN属性。

这是app.config;

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Add("TNS_ADMIN", @"anylocation");
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

当前我正在尝试做的是这个

{{1}}

但是,这会增加另一个部分。

如何动态更改tnsadmin?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

Your code adds a new section because you're telling it to

Instead of

config.AppSettings.Settings.Add("TNS_ADMIN", @"anylocation");

Try

config.AppSettings.Settings["TNS_ADMIN"].Value = "NewValue";

Change NewValue to whatever you're wanting to change it to


You don't have appSettings anywhere within your Config. This could possibly cause the error to be thrown. Won't know for sure if you do not supply the line that is throwing the error. Try wrapping your <settings> with <appSettings>:

<appSettings>
    <version number="*">
        <settings>
            <setting name="TNS_ADMIN" value="asd" />
        </settings>
    </version>
</appSettings>