日期:2014-05-18  浏览次数:20981 次

怎样用GZipStream压缩大文件?
C# code

string strInfileName = @"D:\test.txt";
string strOutfileName = @"D:\test.zip";
FileStream fsInfile = new FileStream(strInfileName, FileMode.Open);
byte[] buff = new byte[(int)fsInfile.Length];
fsInfile.Read(buff, 0, buff.Length);
fsInfile.Close();
FileStream fsOutfile = new FileStream(strOutfileName, FileMode.Create);
GZipStream gzStream = new GZipStream(fsOutfile, CompressionMode.Compress, true);
gzStream.Write(buff, 0, buff.Length);
gzStream.Close();
fsOutfile.Close();



我在网上查到的关于GZipStream压缩的例子大多是这样的.首先把要压缩的文件内容全部输入到byte[]中,然后再将解压后的内容输入到文件流中.但这样的话有多大文件就要占用多大内存.

我想把文件一部分一部分的读入再一部分一部分的将压缩内容输出到文件.但不知道怎么操作.







------解决方案--------------------
C# code

using (FileStream inStream = new FileStream("", FileMode.Open))
using (FileStream outStream = new FileStream("", FileMode.OpenOrCreate))
using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress))
{
    inStream.CopyTo(gzipStream);
    //.net4 以前就读一部份,写一部分,直到完成。
}

------解决方案--------------------
VB.NET code

   Private Shared Sub exeCompress(ByVal orgStream As System.IO.Stream, ByVal cmpStream As System.IO.Stream)
  Dim zipStream As System.IO.Compression.GZipStream = New System.IO.Compression.GZipStream(cmpStream, System.IO.Compression.CompressionMode.Compress)
        Dim buffer As Byte() = New Byte(1024) {}
        While True
            Dim bytesRead As Integer = orgStream.Read(buffer, 0, 1024)
            If bytesRead = 0 Then
                Exit While
            End If
            zipStream.Write(buffer, 0, bytesRead)
        End While
        zipStream.Flush()
        zipStream.Close()
    End Sub