【发布时间】:2015-08-21 19:24:41
【问题描述】:
对于我的 c# windows 窗体应用程序,我想在客户端计算机上保留一些用户数据。我的步骤应该是什么(例如本地数据库、xml 文件),哪一个最安全。
【问题讨论】:
对于我的 c# windows 窗体应用程序,我想在客户端计算机上保留一些用户数据。我的步骤应该是什么(例如本地数据库、xml 文件),哪一个最安全。
【问题讨论】:
我会使用 App.config 并使用 ConfigurationManager.AppSettings 类访问设置。
应用程序配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="Setting1" value="true"/>
<add key="Setting2" value="value"/>
</appSettings>
</configuration>
使用以下命令从您的应用程序访问设置
bool setting1 = Convert.ToBolean(ConfigurationManager.AppSettings["Setting1"]);
string setting2 = ConfigurationManager.AppSettings["Setting2"];
要更新设置,请创建静态辅助方法
public static void UpdateAppSetting(string key, string value)
{
var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
有关更多示例,请参见下面的链接。
【讨论】:
我用于所有程序在启动和关闭时加载和保存设置的代码:
private void Window_Closing(object sender, CancelEventArgs e)
{
SaveAppSettings();
}
private void LoadAppSettings()
{
if (Properties.Settings.Default.LastWindowSize.Width > System.Windows.SystemParameters.WorkArea.Width)
this.Width = System.Windows.SystemParameters.WorkArea.Width - 1; // stay within screen resolution
else
this.Width = Properties.Settings.Default.LastWindowSize.Width;
if (Properties.Settings.Default.LastWindowSize.Height > System.Windows.SystemParameters.WorkArea.Height)
this.Height = System.Windows.SystemParameters.WorkArea.Height - 1; // stay within screen resolution
else
this.Height = Properties.Settings.Default.LastWindowSize.Height;
if (Properties.Settings.Default.LastWindowPos.X > 0) // keep it sane, otherwise window appears to disappear
this.Left = Properties.Settings.Default.LastWindowPos.X;
if(Properties.Settings.Default.LastWindowPos.Y > 0)
this.Top = Properties.Settings.Default.LastWindowPos.Y;
}
private void SaveAppSettings()
{
if (this.WindowState == WindowState.Normal)
{
Properties.Settings.Default.LastWindowPos = new System.Drawing.Point((int)this.Left, (int)this.Top);
Properties.Settings.Default.LastWindowSize = new System.Drawing.Size((int)this.Width, (int)this.Height);
}
else
{
Properties.Settings.Default.LastWindowPos
= new System.Drawing.Point((int)this.RestoreBounds.Left, (int)this.RestoreBounds.Top);
Properties.Settings.Default.LastWindowSize
= new System.Drawing.Size((int)this.RestoreBounds.Width, (int)this.RestoreBounds.Height);
}
Properties.Settings.Default.Save();
}
自从我使用 VMWare Fusion 以来,我对合理的大小进行了一些检查。如果融合窗口小于最后一个应用程序大小,您可能会遇到无法再正确调整应用程序大小的情况。这应该让您了解一种做事方式。
【讨论】:
处理此问题的内置方法是 settings 类。
在项目文件中甚至还有一个“设置”选项卡,您可以为您的应用输入值。在运行时访问它们,例如
Width = Settings1.Default.Width;
Height = Settings1.Default.Height;
Top = Settings1.Default.Top;
Left = Settings1.Default.Left;
Save() 和 Load() 也可用。
【讨论】: