Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
app.config修改值c#_C#_Console Application_App Config - Fatal编程技术网

app.config修改值c#

app.config修改值c#,c#,console-application,app-config,C#,Console Application,App Config,问题就在这里 公认的答案是 string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location); string configFile = System.IO.Path.Combine(appPath, "App.config"); ExeConfigurationFileMap configFileMap = new ExeConfigur

问题就在这里

公认的答案是

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(); 
但当我尝试实现同样的功能时,我发现了一个奇怪的行为。设置值时,上面的答案抛出
NullReferenceException
config.AppSettings.Settings
计数为零

因此,我将configFile路径设置为项目内部的app.config路径

string configFile = @"D:\App\Schedule\Schedule\App.config";
这将修改项目内的app.config以及bin/debug中的>.exe.config。但我认为这不是一个可行的解决方案,因为应用程序可以部署在任何路径上。因此,硬编码configPath将不起作用

然后,我再次修改了给定的配置文件

string configFile = System.IO.Path.Combine(appPath, "<appname>.exe.config");
string configFile=System.IO.Path.Combine(appPath,.exe.config);
上面的代码只运行并修改项目中的>.exe.config,而不修改app.config

我真的不确定哪个是正确的,或者我遗漏了什么

我使用的是VS2012,c#4.5,它是控制台应用程序。到目前为止,我的控制台中没有其他代码,app.config是

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

这只是对app.config的错误理解。 您希望应用程序修改不正确的源代码

当您运行程序时,它会将
app.config
的副本创建到您的bin/debug或bin/release文件夹中

你的第二个解决方案很好。应用程序正在按预期工作

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

其中:path-是“新值”,appSettings-是App.config中的一部分

是的,我确实理解它,但公认的方法也很好地做到了这一点。为什么它对我不起作用:(我认为公认的答案比我的更优雅