0

在 StackOverflow 上使用几个示例,我认为以下代码将解压缩 gzip 文件,然后读取内存流并将其内容写入控制台。没有发生错误,但我没有得到任何输出。

public static void Decompress(FileInfo fileToDecompress)
        {
            using (FileStream originalFileStream = fileToDecompress.OpenRead())
            {
                string currentFileName = fileToDecompress.FullName;
                string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

                using (FileStream decompressedFileStream = File.Create(newFileName))
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                    {
                        MemoryStream memStream = new MemoryStream();
                        memStream.SetLength(decompressedFileStream.Length);
                        decompressedFileStream.Read(memStream.GetBuffer(), 0, (int)decompressedFileStream.Length);

                        memStream.Position = 0;
                        var sr = new StreamReader(memStream);
                        var myStr = sr.ReadToEnd();
                        Console.WriteLine("Stream Output: " + myStr);
                    }
                }
            }
        }
4

1 回答 1

2

您正在尝试复制一个空流。"decompressedFileStream" 是由 File.Create() 创建的,所以它是空的。将“decompressedFileStream”交换为“decompressionStream”,您将能够在“myStr”中看到您的文件内容。

        public static void Decompress(FileInfo fileToDecompress)
    {
        using (FileStream originalFileStream = fileToDecompress.OpenRead())
        {
            string currentFileName = fileToDecompress.FullName;
            string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

            using (FileStream decompressedFileStream = File.Create(newFileName))
            {
                using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                {
                    MemoryStream memStream = new MemoryStream();
                    //memStream.SetLength(decompressedFileStream.Length); not necessary
                    decompressionStream.CopyTo(memStream);

                    memStream.Seek(0, SeekOrigin.Begin);
                    var sr = new StreamReader(memStream);
                    var myStr = sr.ReadToEnd();
                    Console.WriteLine("Stream Output: " + myStr);
                }
            }
        }
    }

试试这个片段。我使用 CopyTo 而不是 Read 将数据复制到内存流,我使用 Seek() 方法而不是 Position 在内存流的开头返回。

于 2012-12-18T17:36:38.947 回答