首页 > 解决方案 > 将流传递给另一个函数时无法访问关闭的流

问题描述

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

无法访问已关闭的流

这是代码:

第一种方法:

在这里,它使用 File.Open 方法打开一个文件,然后创建一个 memorystream 对象并将 FileStream 复制到 MemoryStream。然后将位置设置为 0(我将位置设置为 0,因为我在解决方案中,但没有帮助)。然后它创建一个类对象并通过将 MemoryStream 传递给它来DocxConvert调用该方法。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
        }
}

ps 我在发布之前在这里搜索了这个错误,但没有一个主题对我有帮助。

通过重新启动PC解决了,代码就可以了。

标签: c#asp.net-mvcstreamfilestreammemorystream

解决方案


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

    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)
        {


        }

    }

推荐阅读