Do we need to close a C# BinaryWriter or BinaryReader in a using block?

社会主义新天地 提交于 2019-12-23 07:38:59

问题


Having this code:

using (BinaryWriter writer = new BinaryWriter(File.Open(ProjectPath, FileMode.Create)))
{
   //save something here
}

Do we need to close the BinaryWriter? If not, why?


回答1:


So long as it's all wrapped up in a using block then you don't need to explicitly call Close.

The using block will ensure that the object is disposed, and the Close and Dispose methods are interchangeable on BinaryWriter. (The Close method just calls Dispose behind the scenes.)




回答2:


Putting it in a using statement as per your code example will call Dispose, which closes the underlying stream, so no. You can see this through Reflector:

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        this.OutStream.Close();
    }
}



回答3:


With the code you have there it will close the file once it exits the using block, so you do not need to call close explcitly.

The only reason not to use the using statement would be if you want the file to still be open after you are done with your BinaryWriter, in which case you should hold on to a reference of it instead of passing it into the constructor like that.




回答4:


The using block will automaticlly close the binary writer and put it in a state to be GC'ed. Using blocks are syntactic sugar for doing the exception handling and closing of the stream yourself.




回答5:


By wrapping the writer up in a using block, the close will automatically happen when the writer is disposed. So in this case, you don't need to explicitly close the writer.



来源:https://stackoverflow.com/questions/1079434/do-we-need-to-close-a-c-sharp-binarywriter-or-binaryreader-in-a-using-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!