C#如何在每秒钟增加值,增量值基于amount.text文件
IDE是VisualStudio2010 我有两个文本文件叫total-cost.txt和amount.txt 内部的文件如下所示:C#如何在每秒钟增加值,增量值基于amount.text文件,c#,windows,visual-studio-2010,textview,text-files,C#,Windows,Visual Studio 2010,Textview,Text Files,IDE是VisualStudio2010 我有两个文本文件叫total-cost.txt和amount.txt 内部的文件如下所示: total-cost.txt 4500000 amount.txt 600 第一个文本文件(total cost.txt)表示将在textbox显示的总成本(textbox名称为totalcost) 第二个文件(amount.txt)表示每秒的增量值 我试图显示total-cost.txt中的总成本,并自动增加amount.txt中设置的每秒钟的值 例如: 4
total-cost.txt
4500000
amount.txt
600
第一个文本文件(total cost.txt)表示将在textbox显示的总成本(textbox名称为totalcost)
第二个文件(amount.txt)表示每秒的增量值
我试图显示total-cost.txt中的总成本,并自动增加amount.txt中设置的每秒钟的值
例如:
4500000在1秒后变成4500600在2秒后变成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();
}
}
}
不知怎的,我只是在文本框中显示了总成本
我不知道如何实现自动增量
让任何人分享想法或解决方案。我非常感激 使用系统;
使用System.IO;
私有void IncrementInt32ValueInFile(字符串文件路径)
{
var currentFileText=File.ReadAllText(文件路径);
if(int.TryParse(currentFileText,out int integerValue))
{
File.writealText(filePath,Convert.ToString(++integerValue));
}
如果无法将文件中的值解析为整数,则引发新异常($“不正确的文件内容。路径:{filePath}”);//如果
}
感谢您的回复。我不懂代码,你能解释一下吗?文件路径是什么意思?是否所有需要替换的文件路径?如果是,应替换哪个文件,以及在完整代码中的何处添加此代码。谢谢。@KimfilePath
是您的amount.txt
文件路径的参数。只需将此方法插入到类中,并在需要的地方使用它。例如:private void IncrementInt32ValueInFile(字符串文件路径){var currentFileText=File.ReadAllText(“amount.txt”);if(int.TryParse(currentFileText,out int integerValue)){File.writealText(“total cost.txt”,Convert.ToString(++integerValue));}抛出新异常(“不正确的文件内容。路径:{filePath}”);//如果文件中的值不能被解析为整数}如果我做错了,请修改它。谢谢。@Kim是的,但是为什么不想使用filePath
参数并直接在File.ReadAllText
方法中替换它呢?用法示例:IncrementInt32ValueInFile(“amount.txt”)亲爱的皮科利诺,我仍然无法在我的程序中正常工作。。。你能帮我通过电子邮件查看我的代码吗?如果给您带来任何不便,您可以忽略它。谢谢。您好,为了可读性,请尽量只发布相关的代码片段,而不是整个类。@Stefan好的,我只想尽可能地把它弄清楚。下次我会被注意到的。谢谢。如果你不使用C语言,C语言标签的用途是什么?@Gerhardh我已经修改过了。谢谢你。