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

后端 未结 6 1514
自闭症患者
自闭症患者 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:18

    Streams are objects that "manage" or "handle" non-garbage collected resources. They (Streams) therefore implement the IDisposable interface that, when used with 'using' will make sure the non-garbage collected resources are clean up. try this:

    using ( StreamWriter outfile = new StreamWriter("../../file.txt") )
    {
       outfile.Write(b64img);
    }
    

    Without the #Close, you can not be sure when the underlying file handle will be properly closed. Sometimes, this can be at app shutdown.

提交回复
热议问题