c# - app.config修改值c#

标签 c# console-application app-config

问题在这里得到解决App.Config change value

接受的答案是

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(); 

但是当我尝试实现相同的功能时,我发现了一个奇怪的行为。上面的答案在设置值时抛出 NullReferenceExceptionconfig.AppSettings.Settings 计数为零。

所以我将configFile路径设置为项目内的app.config路径

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

这会同时修改项目中的 app.config 以及 bin/debug 中的 << appname >>.exe.config。但我不认为这是一个可行的解决方案,因为应用程序可以部署在任何路径上。因此,对 configPath 进行硬编码是行不通的。

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

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

上面的代码只运行和修改<< appname >>.exe.config,而不是项目内部的app.config。

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

我使用的是 VS 2012,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 文件夹中。

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

关于c# - app.config修改值c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30640528/

相关文章:

c++ - 将 Windows C++ 服务器编写为服务或控制台应用程序

c# - 无法使用 EF6 插入\更新

c# - Windows 8 上 App.Config 的路径访问被拒绝。如何更新 App.Config?

c# - .Net 的 Java AST 解析器

C# 和 SQL TOP 查询

c# - NHibernate 3.2 映射中的一对一映射代码

vb.net - 从 VB.Net 中的 app.config 获取动态更新的连接字符串

c# - 将 C# 项目转换为 C++ 项目的 Dll

visual-c++ - Windows 上的 SDL2 窃取了我的 stdout 和 stderr

.net - 我们可以加密整个配置文件吗?