如何在替换同一行的数字的同时写入文本文件

本文关键字:数字 文件 一行 文本 替换 | 更新日期: 2023-09-27 18:28:04

这是我在每分钟的计时器刻度事件间隔中的代码。

postsCounter += 1;
label2.Text = postsCounter.ToString();
label2.Visible = true;
w.WriteLine(postsCounter.ToString());

w是StreamWriter

但取而代之的是每分钟添加一条像这样的新线路

12.3.4.5

我想,然后文字写入文本文件将取代最后一个数字。不要在它附近添加新行或数字,而是像计数器一样替换它。所以最后,当我停止计时器并观看文本文件时,我会看到最后一个数字的一行。

忘了提一下,我在form1的顶部为StreamWrite做了实例,然后在构造函数中,我只写了一行DateTime。现在到文本文件中,我想添加一个空行,然后写数字,最后当我写完数字时,添加另一个空线,然后写DateTime。再次。

在表格1的顶部

int postsCounter = 0;
StreamWriter w = new StreamWriter(@"e:'posts.txt");

在构造函数中

label4.Text = DateTime.Now.ToString();
w.WriteLine(label4.Text.ToString());
label5.Visible = false;
label2.Visible = false;

在计时器滴答事件中

sent = true;
            postsCounter += 1;
            label2.Text = postsCounter.ToString();
            label2.Visible = true;
            w.WriteLine(postsCounter.ToString());
            if (postsCounter == 720)
            {
                label5.Text = DateTime.Now.ToString();
                label5.Visible = true;
                w.WriteLine(label5.Text.ToString());
                w.Close();
                timer1.Stop();
            }

如何在替换同一行的数字的同时写入文本文件

您可以使用System.IO.File.WriteAllText方法来替换每个刻度上的文件内容。例如:

postsCounter += 1;
label2.Text = postsCounter.ToString();
label2.Visible = true;
System.IO.File.WriteAllText(filePath, postsCounter.ToString());

您应该使用不同的方法,如File.WriteAllText,每次调用它时都会替换文件内容。

File.WriteAllText("log.txt", postsCounter.ToString());