首页 > 解决方案 > C#如何每秒增加值,增量值基于amount.text文件

问题描述

IDE 是 Visual Studio 2010。

我有两个名为 total-cost.txt 和 amount.txt 的文本文件,里面的文件如下所示:

total-cost.txt
4500000

amount.txt
600

第一个文本文件(total-cost.txt)表示将显示在文本框(文本框名称为 totalcost)的总成本。

第二个文件 (amount.txt) 表示每秒的增量值。

我正在尝试显示来自 total-cost.txt 的总成本并自动增加在 amount.txt 中设置的每一秒的值

例如:

1 秒后 4500000 变为 2 秒后 4500600 4501200 等等。

如果我将 amount.txt 值从 600 更改为 700 它变成

1 秒后 4500000 变为 2 秒后 4500700 4501400 等等。

该值将保持刷新并仅显示最新的总成本。

问题是我已经在文本框中显示了总成本值,但我不知道如何增加由 amount.txt 设置的值

我所做的编码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;

namespace new_countdown
{
    public partial class Form1 : Form
    {         
        private string TotalCost;
        private int TotalFont;

        public Form1()
        {
            InitializeComponent();
        }

        private void ReadTotalCostFile()
        {
            try
            {
                StreamReader sr = File.OpenText("total-cost.txt");
                TotalCost = sr.ReadToEnd();
                sr.Close();
            }
            catch { }
        }

        private void UpdateDisplay() 
        {
            if (totalcost.Text != TotalCost)
            {
               totalcost.Text = TotalCost;
            }

            if (totalcost.Font.Size != TotalFont && TotalFont != 0)
            { 
                this.totalcost.Font = new System.Drawing.Font("Microsoft Sans Serif",(float)TotalFont,System.Drawing.FontStyle.Bold,
                System.Drawing.GraphicsUnit.Point,((byte)(0)));
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateDisplay();
            ReadTotalCostFile();
        }
   }
}

不知何故,我刚刚在文本框中完成了显示总成本。

我对自动增量没有任何想法。

有没有人分享这个想法或解决方案。我非常感谢它。

标签: c#windowsvisual-studio-2010textviewtext-files

解决方案


using System;
using System.IO;

private void IncrementInt32ValueInFile(string filePath)
{
    var currentFileText = File.ReadAllText(filePath);
    if (int.TryParse(currentFileText, out int integerValue))
    {
        File.WriteAllText(filePath, Convert.ToString(++integerValue));
    }

    throw new Exception($"Incorrect file content. Path: {filePath}"); // If value in file can't be parsed as integer
}

推荐阅读