我正在使用此代码:
for ($number=0; $number < 5; $number++) {
StreamWriter x = new StreamWriter("C:\\test.txt");
x.WriteLine(number);
x.Close();
}
如果 test.txt 中有某些内容,此代码不会覆盖它。我有两个问题:
尝试 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);
StreamWriters 默认行为是创建一个新文件,或者覆盖它(如果存在)。 要附加到文件,您需要使用接受布尔值并将其设置为 true 的重载。 在您的示例代码中,您将重写 test.txt 5 次。
using(var sw = new StreamWriter(@"c:\test.txt", true))
{
for(int x = 0; x < 5; x++)
{
sw.WriteLine(x);
}
}
您可以将第二个参数传递给
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");
您可以首先使用 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);
那么你的代码的结果是什么?
我希望该文件只包含数字 4,因为默认行为是创建/覆盖,但你是说它不覆盖?
您应该能够通过执行您正在执行的操作来使其覆盖文件,并且您可以通过使用 FileMode.Append 创建 FileStream 来进行追加。