Why must I Close() a file in C#?

后端 未结 6 1535
自闭症患者
自闭症患者 2021-02-20 12:47

I know this might seem silly, but why does the following code only work if I Close() the file? If I don\'t close the file, the entire stream is not written.

Steps:

6条回答
  •  半阙折子戏
    2021-02-20 13:16

    Because you are using a streamwriter and it doesn't flush the buffer until you Close() the writer. You can specify that you want the writer to flush everytime you call write by setting the AutoFlush property of the streamwriter to true.

    Check out the docs. http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx

    If you want to write to a file without "closing", I would use:

    System.IO.File
    

提交回复
热议问题