C# 如何在应用程序打开时更改应用程序设置(设置)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1170850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change application settings (Settings) while app is open?
提问by agnieszka
I've written a class that should allow me to easily read and write values in app settings:
我编写了一个类,它应该允许我在应用程序设置中轻松读取和写入值:
public static class SettingsManager
{
public static string ComplexValidationsString
{
get { return (string)Properties.Settings.Default["ComplexValidations"]; }
set
{
Properties.Settings.Default["ComplexValidations"] = value;
Properties.Settings.Default.Save();
}
}
the problem is the value isn't really saved, I mean it is not changed when I exit the application and run it again. What can I do to ensure that the saved value persists between closing and opening again?
问题是该值并没有真正保存,我的意思是当我退出应用程序并再次运行它时它没有改变。我该怎么做才能确保保存的值在关闭和再次打开之间保持不变?
采纳答案by Henk Holterman
You should check
你应该检查
Properties.Settings.Default.Properties["ComplexValidations"].IsReadOnly
It is probably true, this is what Roland means with "Application Scope". Save will fail silently. Take a look at Project|Properties|Settings, 3rd column.
大概是这样,这就是罗兰所说的“应用范围”的意思。保存将无声地失败。查看项目|属性|设置,第 3 列。
回答by Woland
settings scope must be user not application
设置范围必须是用户而不是应用程序
回答by Graham Clark
Are you sure it's not saving the changes? The [ProgramName].exe.config file in the bin folder won't be updated. The acutal file used is usually put in C:\Documents and Settings\[user]\Local Settings\Application Data\[company name]\[application].exe[hash string]\[version]\user.config
. I know when I tried this kind of thing it took me a while to realise this was the file that was getting updated.
你确定它没有保存更改吗?bin 文件夹中的 [ProgramName].exe.config 文件不会更新。使用的实际文件通常放在C:\Documents and Settings\[user]\Local Settings\Application Data\[company name]\[application].exe[hash string]\[version]\user.config
. 我知道当我尝试这种事情时,我花了一段时间才意识到这是正在更新的文件。
回答by Jader Dias
I just tested a User Setting and it is persisted if you run this Console app twice:
我刚刚测试了一个用户设置,如果你运行这个控制台应用程序两次,它会持续存在:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Settings1.Default.Setting);
Console.ReadLine();
Settings1.Default.Setting = "A value different from app.config's";
Settings1.Default.Save();
}
}
Just try it out. It won't take a minute.
试试吧。不会花一分钟。