如何在C#应用程序中用程序修改设置文件(app.config)的信息
本文关键字:app 文件 config 信息 设置 程序修改 应用程序 | 更新日期: 2023-09-27 18:19:51
我们正在深入研究基于C#窗口的application.net 4环境。在我的应用程序中,我想用程序更新设置文件(app.config)属性。实际上,我们创建了一个用户界面(文本框)。因此,用户将在文本框中输入新的配置信息。单击保存按钮时,我想永久更新设置文件中的此值。
例如:
我的设置文件中有加密密钥。假设,用户可以使用该界面输入新的加密密钥,然后它将自动更新设置文件加密密钥值。
这可能吗?
首先,您必须添加此引用: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
的相关文本框。
编辑app.config的最佳方法是创建一个安装项目。
安装项目将以管理员身份运行,并允许写入程序文件文件夹。不允许常规标准用户写入程序文件文件夹。
在安装过程中,您可以从用户那里收集有关应该在配置文件中设置的值的信息,并可以搜索正确的文件夹。
请注意,如果要更改每个用户的设置,则不会遇到此问题,因为用户设置已写入用户的配置文件中。
是否要在运行时编辑配置文件?这是可能的。使用System.Configuration程序集中的ConfigurationManager类(添加对它的引用)。你可以获得任何你喜欢的部分,例如appSettings并对其进行修改。
这可能有助于
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appsettings = (AppSettingsSection)config.GetSection("appSettings");
appsettings.Settings["Key"].Value = "value";
config.Save(ConfigurationSaveMode.Modified);