【问题标题】:Unable To Add Value To Custom App.Config Section无法为自定义 App.Config 部分添加价值
【发布时间】:2022-01-18 23:10:09
【问题描述】:

我对此完全束手无策,基本上已经尝试了所有方法。我也没有看到任何关于这样做的现有 stackoverflow 线程。

我的 C# 项目有一个 app.config 文件,它存储了用户可以创建和添加到的服务器列表。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="servers" type="System.Configuration.AppSettingsSection" />
    </configSections>
    <servers>
        <add key="server" value="678,true,true"/>
    </servers>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
    </startup>
    <appSettings>
        <add key="nightmode" value="Dark"/>
        <add key="theme" value="Red"/>
    </appSettings>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="ControlzEx" publicKeyToken="69f1c32f803d307e" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

((NameValueCollection)ConfigurationManager.GetSection("servers")).Add("server", $"{port}," + $"{ (dialogResult1 == MessageDialogResult.Affirmative) },{dialogResult2 == MessageDialogResult.Affirmative}");

当用户在“服务器”部分添加新密钥时,会引发以下异常。

System.Configuration.ConfigurationErrorsException: 'The configuration is read only.'

我很困惑为什么会这样

【问题讨论】:

标签: c# xml wpf


【解决方案1】:

我最终生成了自己的 XML 配置,因为这似乎是做事的最佳方式。

【讨论】:

    【解决方案2】:

    你可以试试:

    Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
    config.AppSettings.Settings.Add("test", "propertyValue");
    
    config.Save(ConfigurationSaveMode.Modified, true);
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
    
    string test = ConfigurationManager.AppSettings["test"];
    

    这将获取 de appsettings 部分的值。

    Ps.:你需要安装包 System.Configuration.ConfigurationManager。

    【讨论】:

    • OP 正在尝试写入,而不是读取
    • 代码不完整,见谅。
    猜你喜欢
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2012-10-28
    • 2011-02-26
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多