【问题标题】:how to overwrite data in a txt file? [duplicate]如何覆盖txt文件中的数据? [复制]
【发布时间】:2011-09-20 16:02:25
【问题描述】:

可能重复:
Can any one tell why the previous data is still displayed while saving data using StreamWriter

我有 WPF C# 应用程序,它读取和写入 .txt 文件,我知道如何写行,但我知道如何覆盖已经是文件的文本。这就是我要写入文本文件下一行的内容,但我想越过这些行而不仅仅是写入下一行,谢谢。

using (StreamWriter newTask = new StreamWriter("test.txt", true)) 
{
    newTask.WriteLine(name[i].ToString());    
}

【问题讨论】:

  • 您要覆盖整个文件,还是只覆盖顶部的行?

标签: c# text streamwriter overwrite


【解决方案1】:

需要将第二个参数改为false:

using (StreamWriter newTask = new StreamWriter("test.txt", false)){ 
        newTask.WriteLine(name[i].ToString());
}

【讨论】:

  • 当您的目标是替换文件的所有内容,然后新内容包含的行数少于旧内容时,该怎么办?会覆盖整个文件,还是保留旧文件的剩余行?
  • 它将替换整个文件。
【解决方案2】:

您将true 作为append 参数传递。

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 2019-04-27
    • 2014-08-13
    • 2012-06-18
    • 2012-11-23
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多