Writing to txt file with StreamWriter and FileStream

前端 未结 2 1670
青春惊慌失措
青春惊慌失措 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: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#?

提交回复
热议问题