gpt4 book ai didi

ftp - 使用 GZipStream 计算进度(条)

转载 作者:行者123 更新时间:2023-12-02 07:07:00 25 4
gpt4 key购买 nike

我正在从某个慢速源(如 FTP 服务器)读取 .gz 文件,并立即处理接收到的数据。看起来像这样:

FtpWebResponse response = ftpclientRequest.GetResponse() as FtpWebResponse;
using (Stream ftpStream = response.GetResponseStream())
using (GZipStream unzipped = new GZipStream(ftpStream, CompressionMode.Decompress))
using (StreamReader linereader = new StreamReader(unzipped))
{
String l;
while ((l = linereader.ReadLine()) != null)
{
...
}
}

我的问题是显示准确的进度条。我可以提前获得压缩的 .gz 文件大小,但我不知道未压缩的内容有多大。逐行读取文件我很清楚读取了多少未压缩字节,但我不知道这与压缩文件大小有何关系。

那么,有没有办法从 GZipStream 获取文件指针前进到压缩文件中的距离?我只需要当前位置,即在读取文件之前可以获取的 gz 文件大小。

最佳答案

您可以在其中插入一个流,计算 GZipStream 已读取的字节数。

  public class ProgressStream : Stream
{
public long BytesRead { get; set; }
Stream _baseStream;
public ProgressStream(Stream s)
{
_baseStream = s;
}
public override bool CanRead
{
get { return _baseStream.CanRead; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
_baseStream.Flush();
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int rc = _baseStream.Read(buffer, offset, count);
BytesRead += rc;
return rc;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}

// usage
FtpWebResponse response = ftpclientRequest.GetResponse() as FtpWebResponse;
using (Stream ftpStream = response.GetResponseStream())
using (ProgressStream progressStream = new ProgressStream(ftpstream))
using (GZipStream unzipped = new GZipStream(progressStream, CompressionMode.Decompress))
using (StreamReader linereader = new StreamReader(unzipped))
{
String l;
while ((l = linereader.ReadLine()) != null)
{
progressStream.BytesRead(); // does contain the # of bytes read from FTP so far.
}
}

关于ftp - 使用 GZipStream 计算进度(条),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/412785/

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