简体   繁体   English

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

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

In a Console Application project Im trying to write values to the app.config file and save it permanently but are only able to save it in memory. 在控制台应用程序项目中,我试图将值写入app.config文件并永久保存,但只能将其保存在内存中。 I've tried all the solutions in Write values in app.config file but none works for me. 我已经尝试过在app.config文件写入值中的所有解决方案,但没有一个适合我。

Any ideas what to do to make the change be permanently? 有什么想法可以使更改永久化吗?

app.config file: app.config文件:

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

Class with two methods only saving value to memory: 具有两种方法的类仅将值保存到内存:

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

}

Simple test that writes out the changes but when rebuild the project or opening app.config in notepad the changes are not saved: 一个简单的测试,它记录了更改,但是当重建项目或在记事本中打开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"));
}

As far as i know information from app.config is used while creating program but app.config keys and values are read-only, but you don't have to use app.config to store values in app, try using this: 据我所知,创建程序时会使用来自app.config信息,但是app.config键和值是只读的,但是您不必使用app.config将值存储在app中,请尝试使用此方法:

step 1 第1步
go to solution explorer -> Properties -> Settings and create settings file. 转到solution explorer -> Properties -> Settings并创建设置文件。
step 2 第2步
add settings you want to use 添加您要使用的设置
step 3 第三步
Use in code 在代码中使用

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

read value of setting: 读取设置值:
var name = Settings.Default.Name1;

seting value of setting: 设定值:
Settings.Default.Name1 = value;

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

Hope it helped you. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM