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

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

    C# doesn't have automatic deterministic cleanup. You have to be sure to call the cleanup function if you want to control when it runs. The using block is the most common way of doing this.

    If you don't put in the cleanup call yourself, then cleanup will happen when the garbage collector decides the memory is needed for something else, which could be a very long time later.

    using (StreamWriter outfile = new StreamWriter("../../file.txt")) {
        outfile.Write(b64img);
    } // everything is ok, the using block calls Dispose which closes the file
    

    EDIT: As Harvey points out, while the cleanup will be attempted when the object gets collected, this isn't any guarantee of success. To avoid issues with circular references, the runtime makes no attempt to finalize objects in the "right" order, so the FileStream can actually already be dead by the time the StreamWriter finalizer runs and tries to flush buffered output.

    If you deal in objects that need cleanup, do it explicitly, either with using (for locally-scoped usage) or by calling IDisposable.Dispose (for long-lived objects such as referents of class members).

提交回复
热议问题