我正在编写database
备份功能,从System.Diagnostics.Process object
,从StandardOutput (StreamReader)
属性读取。我已成功写入纯文件。C#缓冲GZipStream压缩
//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();
但是,当我更改为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();
所得GZip
文件不完整/断开。当用7zip
进行解压缩,然后用notepad++
打开时,几乎所有的文本都很好,只有靠近文件末尾的一些字节丢失。我不确定,但也许错误是:zipStream.Write(enc.GetBytes(buff), 0, enc.GetByteCount(buff));
也许与enc.GetByteCount(buff)
有关。
读取缓冲为多线程,用于处理大文件。那么......为什么最后的字节会丢失?我在哪里做错了?
有什么可疑的是,你从来没有关闭/处置你的'zipStream'。这可能没有必要,但这是我第一次尝试。 – hvd
是的,你正在关闭一些未显示的'fs',但可能是底层文件流。如果不让GZipStream完成工作,你无法关闭它。总是关闭最后一个,而不是链中的第一个。 –
fs是代码片段顶部的FileStream。 –