C# Settings.Default.Save() 不保存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16881415/
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
C# Settings.Default.Save() not saving?
提问by
this bug is pretty unusual. Basically my code will change the Settings.Default.Examplethen save and restart the program. Then when it loads, it shows a message box. However oddly, it shows a empty value when the form loads.
这个错误很不寻常。基本上我的代码将更改Settings.Default.Example然后保存并重新启动程序。然后当它加载时,它会显示一个消息框。然而奇怪的是,它在表单加载时显示一个空值。
Here is my code:
这是我的代码:
Main.cs
private void Button1_Click(object sender, EventArgs e)
{
Settings.Default.Example = "Somevalue"; //Sets a value to the settings
Settings.Default.Save(); // Save it
MessageBox.Show(Settings.Default.Example); //Confirming it has been saved
Application.Restart();
}
private void Main_Load(object sender, EventArgs e)
{
MessageBox.Show(Settings.Default.Example); // Here is the weird part, it shows empty.
}
The MessageBoxwill show "Somevalue" when the button was clicked then the applcation restarts and the MessageBoxthat showed was empty. However repeating the process by clicking the button once more and restarting it does show the "Somevalue" MessageBox. Please help! Many Thanks!
该MessageBox会显示“someValue中”单击时按钮,然后在重新启动的applcation和MessageBox那表明是空的。但是,通过再次单击按钮并重新启动它来重复该过程确实会显示 "Somevalue" MessageBox。请帮忙!非常感谢!
回答by Mare Infinitus
Please have a look at this Question
请看看这个问题
Especially, try out the following code from an answer there:
特别是,从那里的答案中尝试以下代码:
using System.Configuration; // Add a reference to System.Configuration.dll
...
var path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
Also, check out this overview, perhaps you ran into some limitation which is not easy to tell from your question.
另外,请查看此概述,也许您遇到了一些从您的问题中不容易看出的限制。
This codeproject articlemight be of some help.
这篇 codeproject 文章可能会有所帮助。
回答by Scott Selby
did you try calling ConfigurationManager.RefreshSectionbefore checking that it got saved ad you could try it again after the reload
ConfigurationManager.RefreshSection在检查它是否保存了广告之前,您是否尝试过调用您可以在重新加载后再次尝试
回答by Damith
If you need to test your application how actually working in this case better to run the exe file. When you run on visual studio on debug mode when those settings saving it will take some time. Go to debug folder and run the exe you will get the messages as expected.
如果您需要测试您的应用程序在这种情况下如何实际工作,最好运行 exe 文件。当您在调试模式下在 Visual Studio 上运行时,保存这些设置需要一些时间。转到调试文件夹并运行 exe,您将按预期获得消息。
回答by David Rettenbacher
Maybe you ran the same mistake as I did: setting the setting's scopeto Application. Those kind of settings are notsaved.
也许你和我犯了同样的错误:将设置设置scope为Application. 这些设置不会被保存。
Set it to Userto solve the problem.
将其设置User为解决问题。
回答by MaurGi
rene is correct - you need to call Default.Reloadafter calling the Savemethod:
rene 是正确的 - 您需要Default.Reload在调用Save方法后调用:
Settings.Default.Save();
Settings.Default.Reload();
Possibly a bug - ?
可能是一个错误 - ?
Posting as a reply to increase visibility -
发布作为回复以提高知名度 -
回答by MaurGi
Using Visual Studio 2013 - there is nothing I could do to make it work reliably, I would call Save and it did not save. Save and then immediately Reload and it still would not retain the values on subsequent runs (probably related to when I stopped debugging could not identify the root cause) - very frustrating, likely there is an underlying bug but I cannot prove it.
使用 Visual Studio 2013 - 我无法让它可靠地工作,我会调用 Save 而它没有保存。保存然后立即重新加载,它仍然不会保留后续运行的值(可能与我停止调试时无法确定根本原因有关) - 非常令人沮丧,可能存在潜在的错误,但我无法证明。
To avoid getting crazy with this I decided to use the registry - the most fundamental way to keep app settings for an app. Recommended for you all. Here is the code:
为了避免对此感到抓狂,我决定使用注册表——这是保存应用程序设置的最基本方法。推荐给大家。这是代码:
public static class RegistrySettings
{
private static RegistryKey baseRegistryKey = Registry.CurrentUser;
private static string _SubKey = string.Empty;
public static string SubRoot
{
set
{ _SubKey = value; }
}
public static string Read(string KeyName, string DefaultValue)
{
// Opening the registry key
RegistryKey rk = baseRegistryKey;
// Open a subKey as read-only
RegistryKey sk1 = rk.OpenSubKey(_SubKey);
// If the RegistrySubKey doesn't exist return default value
if (sk1 == null)
{
return DefaultValue;
}
else
{
try
{
// If the RegistryKey exists I get its value
// or null is returned.
return (string)sk1.GetValue(KeyName);
}
catch (Exception e)
{
ShowErrorMessage(e, String.Format("Reading registry {0}", KeyName.ToUpper()));
return null;
}
}
}
public static bool Write(string KeyName, object Value)
{
try
{
// Setting
RegistryKey rk = baseRegistryKey;
// I have to use CreateSubKey
// (create or open it if already exits),
// 'cause OpenSubKey open a subKey as read-only
RegistryKey sk1 = rk.CreateSubKey(_SubKey);
// Save the value
sk1.SetValue(KeyName, Value);
return true;
}
catch (Exception e)
{
ShowErrorMessage(e, String.Format("Writing registry {0}", KeyName.ToUpper()));
return false;
}
}
private static void ShowErrorMessage(Exception e, string Title)
{
if (ShowError == true)
MessageBox.Show(e.Message,
Title
, MessageBoxButtons.OK
, MessageBoxIcon.Error);
}
}
Usage:
用法:
private void LoadDefaults()
{
RegistrySettings.SubRoot = "Software\Company\App";
textBoxInputFile.Text = RegistrySettings.Read("InputFileName");
}
private void SaveDefaults()
{
RegistrySettings.SubRoot = "Software\Company\App";
RegistrySettings.Write("InputFileName", textBoxInputFile.Text);
}
回答by Global.access.software
If your AssemblyInfo.csfile has a *in Assembly Version then it's refreshing the file every build so you won't see persistence or reliability until you change that to a hard number and rebuild all, then retest everything.
如果您的AssemblyInfo.cs文件有一个*汇编版本,那么它会在每次构建时刷新文件,这样您就不会看到持久性或可靠性,直到您将其更改为硬数字并全部重建,然后重新测试所有内容。
回答by Atilla Baspinar
Beware of calling
小心打电话
Settings.Default.Reload();
after each
每次之后
Settings.Default.Save();
Save() function actually saves your changes to the file but it is not reflected to your running code. Thus, your code keeps the copy of the previous version of the file.
Save() 函数实际上将您的更改保存到文件中,但不会反映到您正在运行的代码中。因此,您的代码保留了该文件先前版本的副本。
When you call Save() at another location in your code, it writes over your first change, effectively reverting your first change back to original value. Very hard to pin down even when debugging.
当您在代码的另一个位置调用 Save() 时,它会覆盖您的第一个更改,有效地将您的第一个更改恢复为原始值。即使在调试时也很难确定。
回答by exesmart
I had the same problem.
我有同样的问题。
To sort out the problem.
去理清问题。
Go to the custom class in Visual Studio. Open the class and Check whether the constructor method.
转到 Visual Studio 中的自定义类。打开类并检查构造函数方法。
If you have a constructor method, it should be parameterless. If you have a constructor with parameters, don;t worry. Create another constructor class without an parameters.
如果你有一个构造函数方法,它应该是无参数的。如果您有带参数的构造函数,请不要担心。创建另一个没有参数的构造函数类。
Repeat this for all sub classes within the class.
对类中的所有子类重复此操作。
Rebuild and run. Now your settings should save.
重建并运行。现在您的设置应该保存。
回答by Bruno Felipe Kouuds
After a full day of researching and studying the subject, I was able to solve this by putting the Configuration to the user:
经过一整天的研究和研究,我能够通过将配置提供给用户来解决这个问题:
Using System.Configuration;
Properties.Settings.Default.strinconn = txt_stringconn.Text;
Properties.Settings.Default.Save ();
Properties.Settings.Default.Upgrade ();
MessageBox.Show ("Saved Settings");
Application.Restart ();

