簡體   English   中英

如何在控制台應用程序中將值永久寫入app.config文件?

[英]How to write value to app.config file permanently in a console application?

在控制台應用程序項目中,我試圖將值寫入app.config文件並永久保存,但只能將其保存在內存中。 我已經嘗試過在app.config文件寫入值中的所有解決方案,但沒有一個適合我。

有什么想法可以使更改永久化嗎?

app.config文件:

<appSettings>
    <add key="test" value="123456" />
</appSettings>

具有兩種方法的類僅將值保存到內存:

public static class ConfigurationHelper
{

    public static void SetSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
    }


    public static void SetSetting2(string key, string value)
    {
        Configuration configuration = ConfigurationManager.
            OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();
        ConfigurationManager.RefreshSection("appSettings");
    }

}

一個簡單的測試,它記錄了更改,但是當重建項目或在記事本中打開app.config時,更改不會保存:

[Test]
public void FirstTest()
{
    Console.WriteLine("Value before: " + ConfigurationHelper.Get<string>("test"));
    ConfigurationHelper.SetSetting2("test", "NewValue");
    Console.WriteLine("Value after: " + ConfigurationHelper.Get<string>("test"));
}

據我所知,創建程序時會使用來自app.config信息,但是app.config鍵和值是只讀的,但是您不必使用app.config將值存儲在app中,請嘗試使用此方法:

第1步
轉到solution explorer -> Properties -> Settings並創建設置文件。
第2步
添加您要使用的設置
第三步
在代碼中使用

using yourNameSpace.Properties;添加using yourNameSpace.Properties;

讀取設置值:
var name = Settings.Default.Name1;

設定值:
Settings.Default.Name1 = value;

保存設置:
Settings.Default.Save();

希望對您有所幫助。

暫無
暫無

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

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