c# - 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();
}
}
}
不知何故,我刚刚在文本框中完成了显示总成本。
我对自动增量没有任何想法。
有没有人分享这个想法或解决方案。我非常感谢它。
解决方案
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
}
推荐阅读
- reactjs - Heroku express + react + webpack - 无法在服务器上运行
- amazon-web-services - 如何在 AWS CodeBuild (buildspec.yml) 中集成 Fortify Scan
- java - 重新部署应用程序时单例会发生什么?
- sql - 合并来自相同 ID 且数量相同的连续日期范围
- google-cloud-platform - 使用服务帐户对从 Cloud Functions 到 Google Endpoints 的请求进行身份验证
- macos - 如何在 install4j 中定义 MacOS 环境变量
- hololens - 如何为另一种语言创建混合现实语音命令配置文件?
- kubernetes - GET_HOSTS_FROM 变量的值是多少?
- c - UndefinedBehaviorSanitizer 因为空指针
- spring-boot - 尝试从部署的任何进程启动实例时出错