gpt4 book ai didi

C# 缓冲 GZipStream 压缩

转载 作者:行者123 更新时间:2023-11-30 23:21:01 28 4
gpt4 key购买 nike

我正在编写一个数据库 备份函数,从System.Diagnostics.Process 对象 读取StandardOutput (StreamReader) 属性。我已成功写入普通文件。

//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) 有关。

读取缓冲用于多线程,用于处理大文件。那么...为什么最后一个字节丢失了?我哪里做错了?

最佳答案

尝试这样的事情:

  • 使用 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;
    }
    }

关于C# 缓冲 GZipStream 压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39503393/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com