Writing to txt file with StreamWriter and FileStream

前端 未结 2 1668
青春惊慌失措
青春惊慌失措 2021-02-12 08:27

I ran into something interesting when using a StreamWriter with a FileStream to append text to an existing file in .NET 4.5 (haven\'t tried any older f

相关标签:
2条回答
  • 2021-02-12 08:48

    It sounds like you did not flush the stream.

    http://msdn.microsoft.com/en-us/library/system.io.stream.flush.aspx

    It looks like StreamWriter writes to a buffer before writing to the final destination, in this case, the file. You may also be able to set the AutoFlush property and not have to explicitly flush it.

    http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush.aspx

    To answer your question, when you use the "using" block, it calls dispose on the StreamWriter, which must in turn call Flush.

    0 讨论(0)
  • 2021-02-12 08:55

    The difference between the two code snippets is the use of using. The using statement disposes the object at the end of the block.

    A StreamWriter buffers data before writing it to the underlying stream. Disposing the StreamWriter flushes the buffer. If you don't flush the buffer, nothing gets written.

    From MSDN:

    You must call Close to ensure that all data is correctly written out to the underlying stream.

    See also: When should I use “using” blocks in C#?

    0 讨论(0)
提交回复
热议问题