简体   繁体   English

C# 缓冲 GZipStream 压缩

[英]C# buffered GZipStream compression

I'm writing a database backup function, reading from a System.Diagnostics.Process object , from StandardOutput (StreamReader) Property.我正在编写一个database备份函数,从System.Diagnostics.Process object读取,从StandardOutput (StreamReader)属性中读取。 I have succeeded in writing to plain file.我已成功写入普通文件。

//This code successfully wrote text files.
StreamWriter f = new StreamWriter(BackupPath);
while (true) {
  //RaiseProgressedEvent(new DBProgressEventArgs(dbsize, progress, "Writing backup file"));

  int buffsize = 512;
  char[] buff = new char[buffsize];
  int count = p.StandardOutput.ReadBlock(buff, 0, buff.Length);
  if (count == 0) break;
  // If no more data, trim the char array
  if (p.StandardOutput.Peek() < 0) buff = (from c in buff where c > 0 select c).ToArray();

  f.Write(buff, 0, count);
  progress += buffsize;
}
f.Close();

But when i change to GZipStream :但是当我更改为GZipStream

//This code yields a broken gzip file.
//*2 lines changed: StreamWriter changed into FileStream.
FileStream fs = File.Create(BackupPath);
GZipStream zipStream = new GZipStream(fs, CompressionMode.Compress, true);

while (true) {
  RaiseProgressedEvent(new DBProgressEventArgs(dbsize, progress, "Writing backup file"));

  int buffsize = 512;
  char[] buff = new char[buffsize];
  int count = p.StandardOutput.ReadBlock(buff, 0, buff.Length);
  if (count == 0) break;
  if (p.StandardOutput.Peek() < 0) buff = (from c in buff where c > 0 select c).ToArray();

  //With UTF 8 Encoding, write to gzipstream.
  //f.write changed into the following 2 lines:
  Encoding enc = Encoding.UTF8;
  zipStream.Write(enc.GetBytes(buff), 0, enc.GetByteCount(buff));

  progress += buffsize;
}
fs.Close();

The resulting GZip file is incomplete/broken.生成的GZip文件不完整/损坏。 When decompressed with 7zip and then opened with notepad++ , almost all the text is good, only some bytes near the ending of the file are lost.7zip解压,再用notepad++打开,几乎所有的文字都是好的,只是文件末尾附近的一些字节丢失了。 I am not sure, but perhaps the error is near: zipStream.Write(enc.GetBytes(buff), 0, enc.GetByteCount(buff));我不确定,但也许错误接近: zipStream.Write(enc.GetBytes(buff), 0, enc.GetByteCount(buff)); Perhaps something to do with the enc.GetByteCount(buff) .也许与enc.GetByteCount(buff)

The reading is buffered for multithreading, for handling large files.读取缓冲用于多线程,用于处理大文件。 So... why did the last bytes are lost?那么......为什么最后一个字节丢失了? Where did i do wrong?我哪里做错了?

Try something like:尝试类似:

  • Use a constructor of GZipStream , which close the FileStream post Dispose使用GZipStream的构造GZipStream ,它关闭FileStream post Dispose

     using(FileStream fs = File.Create(BackupPath)) using(GZipStream zipStream = new GZipStream(fs, CompressionMode.Compress, false)) { while (true) { RaiseProgressedEvent(new DBProgressEventArgs(dbsize, progress, "Writing backup file")); int buffsize = 512; char[] buff = new char[buffsize]; int count = p.StandardOutput.ReadBlock(buff, 0, buff.Length); if (count == 0) break; if (p.StandardOutput.Peek() < 0) buff = (from c in buff where c > 0 select c).ToArray(); //With UTF 8 Encoding, write to gzipstream. //f.write changed into the following 2 lines: Encoding enc = Encoding.UTF8; zipStream.Write(enc.GetBytes(buff), 0, enc.GetByteCount(buff)); progress += buffsize; } }

If what you want is Zip the file in same folder then I try the code below is working.如果您想要的是将文件压缩在同一文件夹中,那么我尝试使用下面的代码。

    private void button1_Click(object sender, EventArgs e)
    {

        try
        {
            FileInfo fi = new FileInfo(@"F:\Harris\abc.txt");
            FileStream fs = File.OpenRead(@"F:\Harris\abc.txt");
            using (FileStream compressedFileStream = File.Create(fi.FullName + ".gz"))
            {
                using (GZipStream compressionStream = new GZipStream(compressedFileStream,
                System.IO.Compression.CompressionMode.Compress, true))
                {
                    fs.CopyTo(compressionStream);
                }
            }//end using

            MessageBox.Show("Done");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally { }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM