C# 在将 GZipStream 复制到 MemoryStream 时无法访问已关闭的流

C# Cannot access a closed stream while copying GZipStream to MemoryStream

我一直在尝试将 GZipStream 转换为 MemoryStream,然后将其转换为字节数组,而无需将任何文件写入硬盘。我一直在尝试将其复制到 MemoryStream,但出现此错误:未处理的异常:System.ObjectDisposedException:无法访问已关闭的流。

我已经查看了其他一些解决方案,但我无法将它们成功实施到我想要完成的目标中。

GZipStream decompressedStream = Decompress(new FileInfo(args[0]));
        using (var finalStream = new MemoryStream())
        {
            decompressedStream.CopyTo(finalStream);
            byte[] decompressedBytes = new byte[finalStream.Length];
        }

编辑:有人想让我添加 Decompress() 的代码,所以这里是

public static GZipStream Decompress(FileInfo fileToDecompress)
    {
        using (FileStream originalFileStream = fileToDecompress.OpenRead())
        {
            string currentFileName = fileToDecompress.FullName;
            string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length) + " (decompressed)";
            using (FileStream decompressedFileStream = File.Create(newFileName))
            {
                using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                {
                    return decompressionStream;
                }
            }
        }
    }

问题在这里:

using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
     return decompressionStream;
}

using 语句(参见 this 文章)处理流,您不能在块外使用它。将您的 MemoryStream 处理移到此块中,并从该方法中移动 return byte[]

像这样的东西应该可以工作:

public static byte[] Decompress(FileInfo fileToDecompress)
{
    using (FileStream originalFileStream = fileToDecompress.OpenRead())
    {
        string currentFileName = fileToDecompress.FullName;
        string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length) + " (decompressed)";
        using (FileStream decompressedFileStream = File.Create(newFileName))
        {
            using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
            using (var finalStream = new MemoryStream())
            {
                decompressionStream.CopyTo(finalStream);
                return finalStream.ToArray();
            }
        }
    }
}