【问题标题】:Modifying app.config at runtime throws exception在运行时修改 app.config 会引发异常
【发布时间】:2012-02-07 02:20:20
【问题描述】:

我正在使用app.config 文件来存储和读取一些参数(sql server 实例名称、用户、密码、日志目录等)。现在,我需要修改一些取决于用户并管理它的参数,但前提是我从 bin/release 目录运行.exe

当我创建设置并安装我的应用程序时,我无法更改此参数 - 它会抛出 TargetInvocationException。我尝试以管理员身份运行我的应用,但没有成功。

我目前使用的代码如下:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("username");
config.AppSettings.Settings.Add("username", this.Config.Username);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

我尝试了一些在 stackoverflow 上找到的其他解决方案,但都没有成功。

【问题讨论】:

  • 当您运行代码时,您拥有的 this.Config.Username.. 的值是什么??
  • 这是一个非常经典的 UAC 陷阱。您可以在开发机器上调试程序时修改该文件,但安装后它无法工作。 c:\program files 中的文件不可写。您将需要一个单独的程序来编辑文件,以便它可以请求 UAC 提升。或者不使用设置来存储此信息,AppData 中的 .xml 文件也可以。
  • @DJKRAZE 用户名值有效。阅读作品。
  • @HansPassant 我会尝试使用单独的程序,或者使用 xml 文件
  • 如果你不喜欢这种方式,也可以考虑使用 XPATH 来实现

标签: c# .net app-config


【解决方案1】:

理想情况下,我们不能在应用程序运行时修改配置条目。

当你从 bin 运行 exe 时,它​​没有修改 *.exe.config 。

而是修改了 *.vshost.exe.Config 文件。

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); returns reference to *.vshost.exe.Config  file

*.exe.config 是只读的,你不能更新这个文件。

【讨论】:

    【解决方案2】:

    试试这样的

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    KeyValueConfigurationCollection settings = config.AppSettings.Settings;
     // update SaveBeforeExit
     settings[username].Value = "newkeyvalue"; //how are you getting this.Config.Username
      ...
     //save the file
     config.Save(ConfigurationSaveMode.Modified);
     //relaod the section you modified
     ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
    

    这里有一些要遵循的步骤例如,如果我想修改基于 DateTime 值的设置..这个简单的解释应该让你很容易遵循。

     1: // Open App.Config of executable   
     2: System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);   
     3: // Add an Application Setting.   
     4: config.AppSettings.Settings.Remove("LastDateChecked");   
     5: config.AppSettings.Settings.Add("LastDateChecked", DateTime.Now.ToShortDateString());   
     6: // Save the configuration file.   
     7: config.Save(ConfigurationSaveMode.Modified);   
     8: // Force a reload of a changed section.   
     9: ConfigurationManager.RefreshSection("appSettings");
    

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多