简体   繁体   English

在C#中,为什么我不能访问此流?

[英]In C#, why can't I access this stream?

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. 我从NHibernate 3 Cookbook(一本很棒的书,顺便说一句)中获得了这段代码,尽管我在勘误表中找不到任何相关内容。 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. 该错误引发sr.ReadToEnd()行。

Found a similar problem after all, Why disposing StreamReader makes a stream unreadable? 毕竟发现了类似的问题, 为什么配置StreamReader会使流不可读? . Basically, I removed the using that was around the reader and all is well. 基本上,我删除了读者周围的用法,一切都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM