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/