app.config modify value c#

旧街凉风 提交于 2020-01-03 16:59:40

问题


The question is addressed here App.Config change value

The accepted answer is

string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);          
string configFile = System.IO.Path.Combine(appPath, "App.config");

ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();         
configFileMap.ExeConfigFilename = configFile;          

System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["YourThing"].Value = "New Value"; 
config.Save(); 

But when I tried to implement the same, I found a weird behavior. The above answer throws NullReferenceException when setting the value. The config.AppSettings.Settings count is zero.

So I set the configFile path to the app.config path inside project

string configFile = @"D:\App\Schedule\Schedule\App.config";

This modifies both app.config inside the project as well as << appname >>.exe.config which is in bin/debug. But I don't think this is a feasible solution as the application can be deployed on any path. So hard coding the configPath will not work.

Then again I modified the configFile as given

string configFile = System.IO.Path.Combine(appPath, "<appname>.exe.config");

The above code runs and modifies only the << appname >>.exe.config and not the app.config inside the project.

I am really not sure which is correct or I am missing any thing.

I am on VS 2012, c# 4.5 and it is console application. As of now there is no other code in my console and the app.config is

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <appSettings>
        <add key="YourThing" value="" />
    </appSettings>
</configuration>

回答1:


This is just a wrong understanding of app.config. You are expecting application to modify your source code which is incorrect.

When you run your program it creates a copy of app.config to your bin/debug or bin/release folder.

Your second solution is fine. Application is working as expected.




回答2:


Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            config.AppSettings.Settings["PresentationFolder"].Value = path;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

Where: path - is "new value", "appSettings" - is Section in App.config



来源:https://stackoverflow.com/questions/30640528/app-config-modify-value-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!