如何使用 StreamWriter 重写文件或追加到文件
我正在使用此代码:
for ($number=0; $number < 5; $number++) {
StreamWriter x = new StreamWriter("C:\\test.txt");
x.WriteLine(number);
x.Close();
}
如果 test.txt 中有某些内容,此代码不会覆盖它。我有两个问题:
- 如何让它覆盖文件?
- 如何附加到同一个文件?
I am using this code:
for ($number=0; $number < 5; $number++) {
StreamWriter x = new StreamWriter("C:\\test.txt");
x.WriteLine(number);
x.Close();
}
If something is in test.txt, this code will not overwrite it. I have two questions:
- How can I make it overwrite the file?
- How can I append to the same file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
StreamWriter 的默认行为是创建一个新文件,或者覆盖它(如果存在)。要附加到文件,您需要使用接受布尔值并将其设置为 true 的重载。在您的示例代码中,您将重写 test.txt 5 次。
StreamWriter's default behavior is to create a new file, or overwrite it if it exists. To append to the file you'll need to use the overload that accepts a boolean and set that to true. In your example code, you will rewrite test.txt 5 times.
尝试使用 FileMode 枚举器:
Try the FileMode enumerator:
您可以将第二个参数传递给
StreamWriter
以启用
或禁用
附加到文件:You can pass a second parameter to
StreamWriter
toenable
ordisable
appending to file:您可以首先使用 FileStream,然后将其传递给 StreamWriter。
或者
You can start by using the FileStream and then passing that to your StreamWriter.
or
那么你的代码的结果是什么?
我希望该文件只包含数字 4,因为默认行为是创建/覆盖,但您是说它没有覆盖?
您应该能够通过执行您正在执行的操作来使其覆盖文件,并且可以通过使用 FileMode.Append 创建 FileStream 来进行追加。
So what is the result of your code?
I would expect the file to contain nothing but the number 4, since the default behavior is to create/overwrite, but you are saying that it is not overwriting?
You should be able to make it overwrite the file by doing what you are doing, and you can append by making a FileStream with FileMode.Append.