使用 Visual Studio 2013 - 我无法让它可靠地工作,我会调用 Save 并且它没有保存。保存然后立即重新加载,它仍然不会保留后续运行的值(可能与我停止调试时无法确定根本原因有关) - 非常令人沮丧,可能存在潜在的错误,但我无法证明这一点。
为了避免对此感到疯狂,我决定使用注册表——为应用程序保留应用程序设置的最基本方法。推荐给大家。这是代码:
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);
}
}
用法:
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);
}