压缩流显示为空

时间:2012-04-27 18:23:31

标签: c# gzip memorystream gzipstream

我需要使用指定大小的批量(不是整体)使用GZip压缩文件。我可以成功填充byte []缓冲区,但在将其复制到压缩流之后,它只会将输出流留空。

public void Compress(string source, string output)
    {
        FileInfo fi = new FileInfo(source);
        byte[] buffer = new byte[BufferSize];
        int total, current = 0;
        using (FileStream inFile = fi.OpenRead())
        {
            using (FileStream outFile = File.Create(output + ".gz"))
            {
                while ((total = inFile.Read(buffer, 0, buffer.Length)) != 0)
                {
                    using (MemoryStream compressedStream = new MemoryStream())
                    {
                        using (MemoryStream bufferStream = new MemoryStream())
                        {
                            CopyToStream(buffer, bufferStream);
                            using (GZipStream Compress = new GZipStream(compressedStream, CompressionMode.Compress, true))
                            {
                                bufferStream.Position = 0;
                                bufferStream.CopyTo(Compress);
                                current += total;
                            }
                            compressedStream.Position = 0;
                            compressedStream.CopyTo(outFile);
                        }
                    }
                }
            }
        }
    }

    static void CopyToStream(byte[] buffer, Stream output)
    {
        output.Write(buffer, 0, buffer.Length);
    }

2 个答案:

答案 0 :(得分:1)

您需要通过在compressedStream.CopyTo(outFile);之前设置Position = 0来回滚compressedStream。

答案 1 :(得分:0)

你试图让事情变得复杂......你不需要额外的MemoryStreams或缓冲......

取自MSDN ... http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx

public static void Compress(FileInfo fi)
    {
        // Get the stream of the source file.
        using (FileStream inFile = fi.OpenRead())
        {
            // Prevent compressing hidden and 
            // already compressed files.
            if ((File.GetAttributes(fi.FullName) 
                & FileAttributes.Hidden)
                != FileAttributes.Hidden & fi.Extension != ".gz")
            {
                // Create the compressed file.
                using (FileStream outFile = 
                            File.Create(fi.FullName + ".gz"))
                {
                    using (GZipStream Compress = 
                        new GZipStream(outFile, 
                        CompressionMode.Compress))
                    {
                        // Copy the source file into 
                        // the compression stream.
                    inFile.CopyTo(Compress);

                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                            fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                    }
                }
            }
        }
    }