简体   繁体   English

在StreamWriter.WriteLine()之后,FileStream.SetLength(0)不会清空文件

[英]After StreamWriter.WriteLine(), FileStream.SetLength(0) does not empty the file

I found a strange problem with FileStream.SetLength(0). 我发现FileStream.SetLength(0)有一个奇怪的问题。 When writing first something to a stream and then calling SetLength(0), the content of the previous write still gets written to the file: 首先向流中写入内容,然后调用SetLength(0)时,先前写入的内容仍将写入文件:

var fileName = "test.txt";
using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 8000, FileOptions.None)) 
{
    using (var streamWriter = new StreamWriter(fileStream, Encoding.Default, bufferSize: 8000, leaveOpen: true)) 
    {
        streamWriter.WriteLine("123");
        fileStream.SetLength(0);
        streamWriter.WriteLine("abc");
    }
}
  var fileContent = File.ReadAllText(fileName);

fileContent becomes "123\\r\\nabc\\r\\n" fileContent变为“ 123 \\ r \\ nabc \\ r \\ n”

Obviously, 123 did not get deleted, even it was written before calling SetLength(0). 显然,即使是在调用SetLength(0)之前写入的,也没有删除123。

Using Seek() or setting the Position to 0 did not help. 使用Seek()或将Position设置为0并没有帮助。

In my application, I am writing to a file, which I keep open. 在我的应用程序中,我正在写入一个文件,该文件一直保持打开状态。 From time to time it can happen that I need to empty the file completely and write a different content. 有时可能需要完全清空文件并写入其他内容。 For performance reasons, I don't want to close the streamWriter. 出于性能原因,我不想关闭streamWriter。

Note to all those guys who love to mark wrongly questions as duplicates 注意所有喜欢将错误的问题标记为重复的人

I made the very frustrating experience on Stackoverflow that a question got marked wrongly as duplicate. 我对Stackoverflow感到非常沮丧,因为一个问题被错误地标记为重复。 I spent a day writing the question, he decides in an instant that it's a duplicate, even when it isn't. 我花了一天的时间写这个问题,他立刻决定是重复的,即使不是。 This usually happens when that guy doesn't truly understand the question and doesn't bother to find the correct answer. 当那个家伙没有真正理解问题并且不费心寻找正确答案时,通常会发生这种情况。 He just feels that a similar problem was solved before on SO. 他只是觉得在SO上解决了类似的问题。 But details matter. 但是细节很重要。 Yes, there are questions about truncating a file using SetLength(0), but they are different in one crucial point: In those examples, SetLength(0) is not preceded by a Write(). 是的,有一些关于使用SetLength(0)截断文件的问题,但是它们在一个关键点上有所不同:在这些示例中,SetLength(0)之前没有Write()。 But this is essential, without it there is no problem. 但这是必不可少的,没有它就没有问题。

Please, please, be very careful and considerate when blocking others from answering by marking a question as duplicate. 请将问题标记为重复来阻止其他人回答时,请非常小心和体贴。

When inspecting FileStream.SetLength() on referencesource.microsoft.com , I noticed this funny looking piece of code: 在referencesource.microsoft.com上检查FileStream.SetLength()时 ,我注意到这段看起来很有趣的代码:

        // Handle buffering updates.
        if (_writePos > 0) {
            FlushWrite(false);
        }

It checks within SetLength() if the internal FileStream buffer has still some write content and writes it first to the file, before executing the rest of SetLength(). 它在SetLength()内检查内部FileStream缓冲区是否仍有写内容,并在执行其余SetLength()之前先将其写入文件。

A very strange behavior. 一个非常奇怪的行为。 I could solve this problem by emptying the internal buffer before calling SetLength() using a Flush() first: 我可以通过先使用Flush()调用SetLength()之前清空内部缓冲区来解决此问题:

  var fileName = "test.txt";
  using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 8000, FileOptions.None)) {
    using (var streamWriter = new StreamWriter(fileStream, Encoding.Default, bufferSize: 8000, leaveOpen: true)) {
      streamWriter.WriteLine("123");
      streamWriter.Flush();
      fileStream.SetLength(0);
      streamWriter.WriteLine("abc");
    }
  }
  var fileContent = File.ReadAllText(fileName);

fileContent is now: "abc\\r\\n" fileContent现在为:“ abc \\ r \\ n”

I would be interested to hear if also other feel this is a bug in FileStream ? 我想知道是否也有人认为这是FileStream中的错误?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Filestream.SetLength()“参数不正确” - Filestream.SetLength() “The parameter is incorrect” StreamWriter.WriteLine()无法正常工作 - StreamWriter.WriteLine() is not working Streamwriter.Writeline和File.WriteAllText乱写文本 - Streamwriter.Writeline and File.WriteAllText writing text out of order “ StreamWriter.WriteLine()”函数是否需要“ lock()”? - Do the “StreamWriter.WriteLine()” function need to “lock()”? 当长度为千兆字节时,FileStream.SetLength(长度)太慢 - FileStream.SetLength(long length) too slow when length is in gigabytes C#:FileStream.SetLength(long)失败,并显示“由于文件系统限制,请求的操作无法完成”(在Windows 10 Home,NTFS上) - C#: FileStream.SetLength(long) fails with “The requested operation could not be completed due to a file system limitation” (on Windows 10 Home, NTFS) StreamWriter.WriteLine 方法切断下一行 - StreamWriter.WriteLine method cuts off next line Streamwriter.WriteLine()并未编写所有内容。 奇怪的输出 - Streamwriter.WriteLine() is not writing everything. Strange output 是否正在对StreamWriter.WriteLine磁盘I / O进行池化? - Is pooling of StreamWriter.WriteLine Disk I/Os happening? 像StreamWriter一样使用FileStream(Write,WriteLine) - Use FileStream Like StreamWriter (Write, WriteLine)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM