簡體   English   中英

如何在C#Windows應用程序中以編程方式修改設置文件(app.config)的信息?

[英]How to modify the information of the Settings file(app.config) programatically in C# windows Application?

我們正在開發基於C#Windows的應用程序.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的最佳方法是創建一個安裝項目。

安裝項目將以Admin身份運行,並且將被允許寫入程序文件文件夾中。 不允許普通的標准用戶寫入程序文件文件夾。

在安裝過程中,您可以從用戶那里收集有關應在配置文件中設置的值的信息,並且可以搜索正確的文件夾。

請注意,如果要更改每個用戶的設置,則不會遇到此問題,因為用戶設置寫在用戶的配置文件中。

這可能會有所幫助

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

是否要在運行時編輯配置文件? 這個有可能。 使用System.Configuration程序集中的ConfigurationManager類(添加對它的引用)。 您會得到自己喜歡的任何部分,例如appSettings並對其進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM