【问题标题】:Updating Counter in App.Config在 App.Config 中更新计数器
【发布时间】:2018-07-30 19:30:30
【问题描述】:

我正在使用 C# 创建一个表单应用程序。这个应用程序应该创建某些文件,这些文件需要有一个递增的数字。因此我想我可以在 app.config 中存储一个 Counter 并在每次创建文件时递增它。

我曾经写过这段代码:

System.Configuration.Configuration _Config = null;
    public Form1()
    {
        InitializeComponent();
        _Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    }

    private void btnNew_Click(object sender, EventArgs e)
    {
        int lCount;
        if (int.TryParse(ConfigurationManager.AppSettings["count"], out lCount))
        {
            _Config.AppSettings.Settings["count"].Value = lCount++.ToString();
            _Config.Save(ConfigurationSaveMode.Modified);

            MessageBox.Show(ConfigurationManager.AppSettings["count"].ToString());
        }
        else
        {
            throw new Exception("Count in Config file is no int");
        }
    }

它不会更新值。我是否需要重新加载配置,或者无论如何在 app.config 中存储计数器值没有任何意义?

谢谢

【问题讨论】:

  • App.config 不适合。您可以使用Settings 或 SQLite 等嵌入式数据库。
  • @Crowcoder 更好地使用 SQLite 方法,以防应用程序发展并成为多用户,修改起来可能非常简单。

标签: c# config app-config


【解决方案1】:

您需要在toString();之前使用lCount++;,否则count总是保存相同的值,您可以尝试在保存新数据时添加ConfigurationManager.RefreshSection方法。

这是您的问题的示例。

int i = 0;
Console.WriteLine("i++:" + i++.ToString()); // will get 0

i = 0;
Console.WriteLine("(++i):"+(++i).ToString()); // will get 1

c# online sample

或者您可以使用(++lCount).ToString() 代替lCount++.ToString()

 _Config.AppSettings.Settings["count"].Value = (++lCount).ToString();

代码如下所示。

System.Configuration.Configuration _Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
int lCount;
if (int.TryParse(ConfigurationManager.AppSettings["count"], out lCount))
{
     lCount++;
    _Config.AppSettings.Settings["count"].Value = lCount.ToString();
    _Config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(_Config.AppSettings.SectionInformation.Name);
}

注意:

我建议你将计数器保存在DB 而不是App.config

【讨论】:

    猜你喜欢
    • 2012-05-04
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2011-11-08
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多