Does disposing streamreader close the stream?

2019-01-01 15:04发布

I am sending a stream to methods to write on, and in those methods I am using a binary reader/wrtier. When the reader/writer gets disposed, either by using or just when it is not referenced, is the stream closed as well??

I would send a BinaryReader/Writer, but I am using a StreamReader too (maybe I should go around that. I am only using that for GetLine and ReadLine). This is quite troublesome if it closes the stream each time a writer/reader gets closed.

7条回答
还给你的自由
2楼-- · 2019-01-01 15:56

Six years late but maybe this might help someone.

StreamReader does close the connection when it is disposed. However, "using (Stream stream = ...){...}" with StreamReader/StreamWriter can result in the Stream being disposed of twice: (1) when the StreamReader object is disposed (2) and when the Stream using block closes. This results in a CA2202 warning when running VS's code analysis.

Another solution, taken directly from the CA2202 page, is to use a try/finally block. Setup correctly, this will only close the connection once.

Near the bottom of CA2202, Microsoft recommends to use the following:

Stream stream = null;
try
{
    stream = new FileStream("file.txt", FileMode.OpenOrCreate);
    using (StreamWriter writer = new StreamWriter(stream))
    {
        stream = null;
        // Use the writer object...
    }
}
finally
{
    if(stream != null)
        stream.Dispose();
}

instead of...

// Generates a CA2202 warning
using (Stream stream = new FileStream("file.txt", FileMode.Open))
using (XmlReader reader = new XmlReader (stream))
{
    // Use the reader object...
}
查看更多
登录 后发表回答