我一直在开发一个程序,通过 LogMeIn 备份(基于 Windows 窗体的程序)自动执行备份检查。我现在需要一种存储用户设置的方法,以便轻松保存信息。我从未使用过有点“内置”的应用程序/用户设置 - 并决定尝试一下,但遇到了问题。
我现在添加了四个设置: IncludeCriteria(Specialized.StringCollection) 排除条件(Specialized.StringCollection) 报告路径(字符串) 报告类型(整数)
但是行为并没有按预期进行(想想看)。在程序中保存一些值后,我使用 VS 2008 设置编辑器返回编辑/查看我的设置值。我的值都没有被存储。虽然我认为这可能是因为这些值只是默认值,但这不是可以存储/读取/更改它们的地方吗?
这是我的加载表单代码(仍然非常不完善):
private void setupForm()
{
txtPath.Text = BackupReport.Properties.Settings.Default.ReportPath == null ? "" : BackupReport.Properties.Settings.Default.ReportPath;
if (BackupReport.Properties.Settings.Default.ReportType == 0)
{
radioHTML.Checked = true;
}
else
radioExcel.Checked = true;
if (BackupReport.Properties.Settings.Default.IncludeCriteria.Count > 0)
{
listIncludeCriteria.DataSource = Properties.Settings.Default.IncludeCriteria;
//foreach (string s in Properties.Settings.Default.IncludeCriteria)
// listIncludeCriteria.Items.Add(s);
}
if (BackupReport.Properties.Settings.Default.ExcludeCriteria.Count > 0)
{
listExcludeCriteria.DataSource = BackupReport.Properties.Settings.Default.ExcludeCriteria;
//foreach (string s in Properties.Settings.Default.ExcludeCriteria)
// listExcludeCriteria.Items.Add(s);
}
}
listIncludeCriteria 只是一个列表框。当用户保存时我调用此方法:
private void saveSettings()
{
//var settings = BackupReport.Properties.Settings;
if (txtPath.Text != "")
{
BackupReport.Properties.Settings.Default.ReportPath = txtPath.Text;
}
if (listIncludeCriteria.Items.Count > 0)
{
//BackupReport.Properties.Settings.Default.IncludeCriteria = (StringCollection)listIncludeCriteria.Items.AsQueryable();
foreach (var i in listIncludeCriteria.Items)
{
if (!isIncludeDuplicate(i.ToString()))
BackupReport.Properties.Settings.Default.IncludeCriteria.Add(i.ToString());
}
}
if (listExcludeCriteria.Items.Count > 0)
{
//BackupReport.Properties.Settings.Default.ExcludeCriteria = (StringCollection)listExcludeCriteria.Items.AsQueryable();
foreach (var i in listExcludeCriteria.Items)
{
if (!isExcludeDuplicate(i.ToString()))
Properties.Settings.Default.ExcludeCriteria.Add(i.ToString());
}
}
if (radioExcel.Checked == true)
BackupReport.Properties.Settings.Default.ReportType = 1;
else
BackupReport.Properties.Settings.Default.ReportType = 0;
BackupReport.Properties.Settings.Default.Save();
//Properties.Settings.Default.Save();
this.DialogResult = DialogResult.OK;
this.Close();
}
奇怪的是,当表单加载时,我第一次输入的路径似乎出现了(ReportPath) - 甚至列表框都填充了我输入的一堆垃圾 - 但我无法在任何地方找到这些值。
如有任何帮助,我们将不胜感激!
乔什
最佳答案
编辑/添加后必须保存
Settings.Default.Save();
一个我经常使用的简单示例
private void Main_Load(object sender, EventArgs e)
{
this.Location = Settings.Default.WindowLocation;
}
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.Default.WindowLocation = this.Location;
Settings.Default.Save();
}
关于c# Properties.Settings.Default 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2842398/