C# 如何每秒递增一个值,递增值是根据 amount.text 文件

标签 c# windows visual-studio-2010 textview text-files

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 变成 4500600 2 秒后 4501200 等等。

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

1 秒后 4500000 变成 4500700 2 秒后 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();
        }
   }
}

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

我对自增没有想法。

让任何人分享想法或解决方案。我非常感激。

最佳答案

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
}

关于C# 如何每秒递增一个值,递增值是根据 amount.text 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098256/

相关文章:

visual-studio - 打开 Microsoft 提供的 Windows Azure 示例至少需要哪些工具?

c# - C#中的字符串插值内的字符串插值导致编译器错误

c# - 用于模糊查找的字典哈希函数

c++ - 如何使用 C++ win32 API 为 Active Directory 中的单个属性设置和获取多个值(数组值)?

windows - Windows/cmd 上的可执行文件类型是什么?他们的优先事项是什么?

Python 在日期时间接近纪元的 Windows 上崩溃

c# - 您可以使用原始 graphQL 语法在 c# 中使用 octokit.net 库查询 github API v4 吗?

c# - SSH.NET - 消息类型 80 无效

asp.net - 如何可靠地跟踪 CSS 的使用情况?

visual-studio-2010 - 始终未命中 Visual Studio 2010 断点