问题描述
我有一些代码应该做的压缩:
I have code that should do the compression:
FileStream fs = new FileStream("g:\\gj.txt", FileMode.Open);
FileStream fd = new FileStream("g:\\gj.zip", FileMode.Create);
GZipStream csStream = new GZipStream(fd, CompressionMode.Compress);
byte[] compressedBuffer = new byte[500];
int offset = 0;
int nRead;
nRead = fs.Read(compressedBuffer, offset, compressedBuffer.Length);
while (nRead > 0)
{
csStream.Write(compressedBuffer, offset, nRead);
offset = offset + nRead;
nRead = fs.Read(compressedBuffer, offset, compressedBuffer.Length);
}
fd.Close();
fs.Close();
和我想这样做,但我想解什么压缩上述的方式。我somethink这样的:
and I think it does, but I want to decompress what was compressed the way above. I do somethink like that:
FileStream fd = new FileStream("g:\\gj.new", FileMode.Create);
FileStream fs = new FileStream("g:\\gj.zip", FileMode.Open);
GZipStream csStream = new GZipStream(fs, CompressionMode.Decompress);
byte[] decompressedBuffer = new byte[500];
int offset = 0;
int nRead;
nRead=csStream.Read(decompressedBuffer, offset, decompressedBuffer.Length);
while (nRead > 0)
{
fd.Write(decompressedBuffer, offset, nRead);
offset = offset + nRead;
nRead = csStream.Read(decompressedBuffer, offset, decompressedBuffer.Length);
}
fd.Close();
fs.Close();
和这里不......我有NREAD = 0 befeore进入循环。 ..我做些什么错?
我使用的测试文件是simpliest文本文件(大小:104字节)...
and here it doesn't... I've got nRead = 0 befeore entering the loop... What I do wrong??The test file I use is the simpliest TEXT file (size: 104 bytes)...
推荐答案
我的第一个想到的是,你还没有关闭 csStream
。如果你使用使用
自动发生这种情况。由于gzip的缓冲区的数据,你可能会缺少一些
My first thought is that you haven't closed csStream
. If you use using
this happens automatically. Since gzip buffers data, you could be missing some.
其次;不增加偏移
;即在缓存(而不是流)的偏移量。离开在0:
Secondly; don't increment offset
; that is the offset in the buffer (not the stream). Leave at 0:
using (Stream fs = File.OpenRead("gj.txt"))
using (Stream fd = File.Create("gj.zip"))
using (Stream csStream = new GZipStream(fd, CompressionMode.Compress))
{
byte[] buffer = new byte[1024];
int nRead;
while ((nRead = fs.Read(buffer, 0, buffer.Length))> 0)
{
csStream.Write(buffer, 0, nRead);
}
}
using (Stream fd = File.Create("gj.new.txt"))
using (Stream fs = File.OpenRead("gj.zip"))
using (Stream csStream = new GZipStream(fs, CompressionMode.Decompress))
{
byte[] buffer = new byte[1024];
int nRead;
while ((nRead = csStream.Read(buffer, 0, buffer.Length)) > 0)
{
fd.Write(buffer, 0, nRead);
}
}
这篇关于GZipStream和解压的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!