Mr *_*ull 3 c# app-config console-application
在控制台应用程序项目中,我尝试将值写入 app.config 文件并将其永久保存,但只能将其保存在内存中。我已经尝试了在 app.config 文件中写入值中的所有解决方案,但没有一个对我有用。
有什么想法可以使改变永久化吗?
应用程序配置文件:
<appSettings>
<add key="test" value="123456" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
具有两种仅将值保存到内存的方法的类:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
写出更改的简单测试,但在重建项目或在记事本中打开 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"));
}
Run Code Online (Sandbox Code Playgroud)
据我所知,app.config在创建程序时使用了来自的信息,但app.config键和值是只读的,但您不必使用它app.config来在应用程序中存储值,请尝试使用此:
步骤 1
转到solution explorer -> Properties -> Settings并创建设置文件。
步骤 2
添加您要使用的设置
步骤 3
在代码中使用
添加using yourNameSpace.Properties;
读取设置值:
var name = Settings.Default.Name1;
设置的设定值:
Settings.Default.Name1 = value;
保存设置:
Settings.Default.Save();
希望它对你有帮助。