0

我需要使用 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);
    }
4

2 回答 2

1

您需要通过在之前设置 Position=0 来倒带压缩流 compressedStream.CopyTo(outFile);

于 2012-04-27T18:33:21.320 回答
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());
                    }
                }
            }
        }
    }
于 2012-04-27T18:40:40.100 回答