The using statement and XmlReader.Create

Are you also fond of using the using statement (e.g. when dealing with streams)? I am, since it kind-of guarantees me that streams are closed when I think they should be closed, even if I do not specify the Dispose() command. You probably noticed the ‘kind-of guarantee’ part. You are right, this is not always the case. It took me a while to find out the the following is not going to work as smooth as expected:

using (var reader = XmlReader.Create(File.Open(fileName, FileMode.Open)))
    { ... }

You probably wonder what’s the problem of the code printed above. I don’t see it too, however, I know there is a problem related to this code. The problem lies in the Create overload used in the example code. It uses default XmlReaderSettings. Unfortunately, this settings do not include having the CloseInput property set to true. You can do the math: no closed file at all! That’s a guarantee for having troubles on the file ‘being in use already’.

The solution to this problem is quite simple:

using (XmlReader reader = XmlReader.Create(File.Open(path, FileMode.Open),
         new XmlReaderSettings { CloseInput = true })) { ... }

How can we call this? A ‘bug’? No, at least not technically spoken. Since the XmlReader creates the stream, it should close it too. The case is, you should not expext it knowing the using statement as most people know it (fail-proofing your code). Since I know this, I am a little bit scared about using using statements without calling the stream’s constructor. You can do so, but be sure it does what you expect it to do… In my opinion, the using statement still remains very helpful, please I do not consider it being as perfect as I thought it to be for years ;)