Question

I got this block of code from the NHibernate 3 Cookbook (an excellent book, btw), and while I couldn't find anyting in the errata about it. I'm getting the error "Cannot access a closed stream":

 var settings = new XmlWriterSettings { Indent = true };
 var serializer = new XmlSerializer(typeof(HbmMapping)); // todo: probably should abstract this out, at least optionally
 using (var memStream = new MemoryStream(2048))
 using (var xmlWriter = XmlWriter.Create(memStream, settings))
 {
     serializer.Serialize(xmlWriter, hbmMapping);
     memStream.Flush();
     memStream.Position = 0;

     using (var sr = new StreamReader(memStream))
     {
         return sr.ReadToEnd();
     }
 }

The error is thrown on the sr.ReadToEnd() line.

Was it helpful?

Solution

Found a similar problem after all, Why disposing StreamReader makes a stream unreadable? . Basically, I removed the using that was around the reader and all is well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top