如何在控制台应用程序中永久地将值写入app.config文件?

时间:2017-02-22 16:01:17

标签: c# console-application app-config

在控制台应用程序项目中我试图将值写入app.config文件并永久保存,但只能将其保存在内存中。 我已经尝试了Write values in app.config file中的所有解决方案,但没有一个适用于我。

任何想法如何永久改变?

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"));
}

1 个答案:

答案 0 :(得分:2)

据我所知,在创建程序时使用来自app.config的信息,但app.config键和值是只读的,但您不必使用app.config来在app中存储值,请尝试使用:

第1步
转到solution explorer -> Properties -> Settings并创建设置文件 第2步
添加您要使用的设置
第3步
在代码中使用

添加using yourNameSpace.Properties;

读取设定值:
var name = Settings.Default.Name1;

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

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

希望它对你有所帮助。

相关问题