【问题标题】:Can't override XML config settings:ConfigurationErrorsException: Invalid key value无法覆盖 XML 配置设置:ConfigurationErrorsException:无效的键值
【发布时间】:2021-01-25 12:40:36
【问题描述】:

我正在尝试构建一个控制台应用程序,用户可以在其中决定是否启用日志记录。为此,我得到了一个 XML 格式的 app.config 文件。代码可以成功读取当前状态,但是当我尝试覆盖“协议”属性时,我在第 27 行得到了给定的异常

我的协议类:


    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Configuration;
    using System.Collections.Specialized;
    
    namespace Bruch
    {
        class Protokoll
        {
            
            public Protokoll()
            {
                string protokollConfigStatus = ConfigurationManager.AppSettings.Get("protokoll");
    
                if (protokollConfigStatus == "unknown")
                {
                    SetzeEinstellung("protokoll", "test");
                };
            }
    
            public static void SetzeEinstellung(string key, string value)
            {
                Configuration configuration =
                    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                configuration.AppSettings.Settings[key].Value = value;
****************configuration.Save(ConfigurationSaveMode.Full, true);     //this line
                ConfigurationManager.RefreshSection("appSettings");
            }
        }
    
    }

我的配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="protokoll" value="unknown" />
   </appSettings>
</configuration>

错误信息:

>System.Configuration.ConfigurationErrorsException: "An error occurred executing the configuration >section handler for configProtectedData."
>
>inner exception:
>ConfigurationErrorsException: Invalid key value.

【问题讨论】:

  • 哪一行代码抛出异常?
  • 对不起,第 27 行,>configuration.Save(ConfigurationSaveMode.Full, true);
  • 旁注:我真的建议在选择方法、类、字段和其他名称时使用英文术语。让国际观众更轻松。
  • 我的大学老师坚持使用德语“说”名字,我应该改的,对不起
  • 没问题。在这种情况下,很明显:)

标签: c# xml config


【解决方案1】:

应用程序范围的设置是只读的,只能在设计时或通过在应用程序会话之间更改 .config 文件来更改。

来源:How To: Write User Settings at Run Time with C#

所以,如果您想在运行时编写设置,您需要的是 user 设置。

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 2011-09-24
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2016-06-18
    相关资源
    最近更新 更多