将流传递给另一个函数时无法访问关闭的流

时间:2018-10-05 08:55:26

标签: c# asp.net-mvc stream filestream memorystream

我需要将流传递给另一个类中的几个函数,但是会引发错误

  

无法访问封闭的流

代码如下:

第一种方法:

在这里使用File.Open方法打开一个文件,然后创建一个memorystream对象,并将FileStream复制到MemoryStream。然后将Position设置为0(我将position设置为0,因为我在解决方案中就是那个,但是对您没有帮助)。然后,它创建一个DocxConvert类的对象,并通过将MemoryStream传递给它来调用Converto方法。

    using (var stream = File.Open(tempPath2, FileMode.Open))
    {
        using(var ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                ms.Position = 0;
                using (var docx = new DocxConvert())
                {
                    return docx.Converto(ms);
                }
            }
    }

DocxConvert类:

获取流,然后通过传递接受的流来调用copyStream方法。

DocxConvert类中的

copyStream方法:它应该将接受的流复制到另一个名为_memoryStream的流中,该流是一个类属性。

    public class DocxConvert
{  

        private MemoryStream _memoryStream = new MemoryStream();

  public bool Converto(Stream stream)
                {
                    try
                    {
                        copyStream(stream);
                        //more code
                    }
                    catch (IOException ex)
                    {
                        Debug.WriteLine(ex);
                    }

                    return true;
                }


       private void copyStream(Stream stream)
        {
            stream.CopyTo(_memoryStream); //here it throws the error
        }
}

p.s。发布之前,我在这里搜索了此错误,但是没有一个主题对我有所帮助。

  

通过重新启动PC来解决,代码正常。

1 个答案:

答案 0 :(得分:1)

我不知道您的问题。但是下面的代码没有例外

    private void button1_Click(object sender, EventArgs e)
    {
        string tempPath2 = Application.StartupPath + "//" + "test.txt";
        using (var stream = File.Open(tempPath2, FileMode.Open))
        {
            using (var ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                ms.Position = 0;

                var docx = new DocxConvert();
                    var isok = docx.Converto(ms);

            }
        }
    }

波纹管是定义在顶部的_memorystream的标语

    MemoryStream _memoryStream = new MemoryStream();
    public bool Converto(Stream stream)
    {
        try
        {
            copyStream(stream);
            //more code
        }
        catch (IOException ex)
        {
          //  Debug.WriteLine(ex);
        }

        return true;
    }
    private void copyStream(Stream stream)
    {
        try
        {
            stream.CopyTo(_memoryStream); 
        }
        catch (Exception)
        {


        }

    }