【问题标题】:How to modify the information of the Settings file(app.config) programatically in C# windows Application?如何在 C# windows 应用程序中以编程方式修改设置文件(app.config)的信息?
【发布时间】:2012-01-07 09:06:19
【问题描述】:

我们正在开发基于 C# windows 的应用程序 .net 4 环境。在我的应用程序中,我想以编程方式更新设置文件(app.config)属性。实际上我们创建了一个用户界面(文本框)。所以,用户将输入新的文本框中的配置信息。单击保存按钮时,我想永久更新设置文件中的此值。

例如:

我的设置文件中有加密密钥。假设用户可以使用该界面输入新的加密密钥,那么它将自动更新设置文件的加密密钥值。

这可能吗?

【问题讨论】:

    标签: c# .net winforms c#-4.0


    【解决方案1】:

    首先你必须添加这个引用:System.Configuration,然后你可以写信给app.config,例如使用这个代码:

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
            ConfigurationSectionGroup applicationSectionGroup = config.GetSectionGroup("applicationSettings");
            ConfigurationSection applicationConfigSection = applicationSectionGroup.Sections["YourApp.Properties.Settings"];
            ClientSettingsSection clientSection = (ClientSettingsSection)applicationConfigSection;
    
            //Encryption Key Configuration Setting
            SettingElement applicationSetting = clientSection.Settings.Get("EncryptionKey");
            applicationSetting.Value.ValueXml.InnerXml = this.textBoxKey.Text.Trim();
    
            applicationConfigSection.SectionInformation.ForceSave = true;
            config.Save();
    
            ConfigurationManager.RefreshSection("applicationSettings");
    

    请记住,您必须先使用 Visual Studio 向导创建 app.config 文件,在此示例中,我调用了加密密钥字段:EncryptionKey 和表单中的相关文本框:textBoxKey .

    【讨论】:

      【解决方案2】:

      编辑 app.config 的最佳方法是创建一个安装项目。

      安装项目将以管理员身份运行,并允许写入程序文件文件夹。不允许普通用户写入程序文件夹。

      在设置过程中,您可以从用户那里收集有关应该在配置文件中设置的值的信息,并且您可以搜索正确的文件夹。

      请注意,如果您想更改每个用户的设置,您不会遇到此问题,因为用户设置已写入用户的配置文件中。

      【讨论】:

        【解决方案3】:

        您想在运行时编辑配置文件吗?这个有可能。使用 System.Configuration 程序集中的 ConfigurationManager 类(添加对它的引用)。你可以得到任何你喜欢的部分,例如appSettings 并修改它们。

        【讨论】:

          【解决方案4】:

          这可能会有所帮助

                  Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                  AppSettingsSection appsettings = (AppSettingsSection)config.GetSection("appSettings");
                  appsettings.Settings["Key"].Value = "value";
                  config.Save(ConfigurationSaveMode.Modified);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-11-01
            • 2012-12-06
            • 2011-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多