MemoryStream的 - 无法访问已关闭的流 [英] MemoryStream - Cannot access a closed Stream

查看:2140
本文介绍了MemoryStream的 - 无法访问已关闭的流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好为什么使用(VAR SW =新的StreamWriter(MS))返回无法访问已关闭的流 除了内存流是这个code顶部。

Hi why using (var sw = new StreamWriter(ms)) returns Cannot access a closed Stream exception. Memory Stream is on top of this code.

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms))
    {                 
        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());                        
        }
    } //error here
}

什么是最好的方式来解决这个问题? 谢谢

What the best way to fix it ? Thanks

推荐答案

这是因为的StreamReader 关闭底层流时会自动被设置的。该使用语句自动执行此操作。

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

不过,的StreamWriter 您使用的是仍然在努力工作流(也行,使用语句作家目前正试图出售的的StreamWriter ,然后试图关闭流)的。

However, the StreamWriter you're using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter, which is then trying to close the stream).

解决这个问题的最好办法是:不要使用使用,不处置的的StreamReader 的StreamWriter 。请参阅<一href="http://stackoverflow.com/questions/1862261/can-you-keep-a-streamreader-from-disposing-the-underlying-stream">this问题。

The best way to fix this is: don't use using and don't dispose of the StreamReader and StreamWriter. See this question.

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    var sr = new StreamReader(ms);

    sw.WriteLine("data");
    sw.WriteLine("data 2");
    ms.Position = 0;

    Console.WriteLine(sr.ReadToEnd());                        
}

如果你觉得不好软件 SR 被当作垃圾回收无需在$ C $布置的C(推荐),你可以做这样的事情:

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

StreamWriter sw = null;
StreamReader sr = null;

try
{
    using (var ms = new MemoryStream())
    {
        sw = new StreamWriter(ms);
        sr = new StreamReader(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;

        Console.WriteLine(sr.ReadToEnd());                        
    }
}
finally
{
    if (sw != null) sw.Dispose();
    if (sr != null) sr.Dispose();
}

这篇关于MemoryStream的 - 无法访问已关闭的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆