如何使用 StreamWriter 重写文件或追加到文件

问题描述 投票:0回答:5

我正在使用此代码:

for ($number=0; $number < 5; $number++) {
    StreamWriter x = new StreamWriter("C:\\test.txt");
                 x.WriteLine(number);
                 x.Close();
}

如果 test.txt 中有某些内容,此代码不会覆盖它。我有两个问题:

  1. 如何让它覆盖文件?
  2. 如何追加到同一个文件?
c# .net streamwriter
5个回答
31
投票

尝试 FileMode 枚举器:

// will append to end of file
FileStream fappend = File.Open("C:\\test.txt", FileMode.Append); 

// will create the file or overwrite it if it already exists
FileStream fcreate = File.Open("C:\\test.txt", FileMode.Create); 

31
投票

StreamWriters 默认行为是创建一个新文件,或者覆盖它(如果存在)。 要附加到文件,您需要使用接受布尔值并将其设置为 true 的重载。 在您的示例代码中,您将重写 test.txt 5 次。

using(var sw = new StreamWriter(@"c:\test.txt", true))
{
    for(int x = 0; x < 5; x++)
    {
        sw.WriteLine(x);    
    }
}

12
投票

您可以将第二个参数传递给

StreamWriter
enable
disable
附加到文件:

C#.Net

using System.IO;

// This will enable appending to file.
StreamWriter stream = new StreamWriter("YourFilePath", true);

// This is default mode, not append to file and create a new file.
StreamWriter stream = new StreamWriter("YourFilePath", false);
// or
StreamWriter stream = new StreamWriter("YourFilePath");

C++.Net(C++/CLI)

using namespace System::IO;

// This will enable appending to file.
StreamWriter^ stream = gcnew StreamWriter("YourFilePath", true);

// This is default mode, not append to file and create a new file.
StreamWriter^ stream = gcnew StreamWriter("YourFilePath", false);
// or
StreamWriter^ stream = gcnew StreamWriter("YourFilePath");

5
投票

您可以首先使用 FileStream,然后将其传递给您的 StreamWriter。

FileStream fsOverwrite = new FileStream("C:\\test.txt", FileMode.Create);
StreamWriter swOverwrite = new StreamWriter(fsOverwrite);

FileStream fsAppend = new FileStream("C:\\test.txt", FileMode.Append);    
StreamWriter swAppend = new StreamWriter(fsAppend);

1
投票

那么你的代码的结果是什么?

我希望该文件只包含数字 4,因为默认行为是创建/覆盖,但你是说它不覆盖?

您应该能够通过执行您正在执行的操作来使其覆盖文件,并且您可以通过使用 FileMode.Append 创建 FileStream 来进行追加。

© www.soinside.com 2019 - 2024. All rights reserved.