在 C# 中,为什么我无法访问该流?

发布于 2024-10-10 17:46:44 字数 645 浏览 5 评论 0原文

我从 NHibernate 3 Cookbook(一本很棒的书,顺便说一句)中得到了这段代码,虽然我在勘误表中找不到任何关于它的内容。我收到错误“无法访问关闭的流”:

 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();
     }
 }

该错误在 sr.ReadToEnd() 行上引发。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何必那么矫情 2024-10-17 17:46:44

毕竟发现了类似的问题,为什么处置 StreamReader 会使流不可读? .基本上,我删除了读者周围的使用,一切都很好。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文