使用DeflateStream压缩byte []时出现问题 [英] Problem compressing byte[] with DeflateStream
问题描述
大家好
我需要使用System.IO.Compression.DeflateStream
压缩byte []
这是我到目前为止的代码:
Hey guys
I need to compress a byte[] with the System.IO.Compression.DeflateStream
Here''s the code I have so far:
byte[] uncompressedCsvFile = File.ReadAllBytes(csvFileName);
byte[] compressedCsvFile;
using (MemoryStream outStream = new MemoryStream())
{
using (DeflateStream compress = new DeflateStream(outStream, CompressionMode.Compress, true))
{
compress.Write(uncompressedCsvFile, 0, uncompressedCsvFile.Length);
compress.Flush();
compress.Close();
}
compressedCsvFile = new byte[outStream.Length];
outStream.Read(compressedCsvFile, 0, (int)outStream.Length);
}
outStream.Lentgh比未压缩的byte []小得多,但是在我尝试读取MemoryStream之后,我的压缩的byte []仅包含0.
在调试器中,我注意到在outStream的非公共成员中,_buffer是预期的大小,并且包含0以外的字节.
我在读取内存流时做错什么了吗?
注意:我需要压缩此数组以通过电线发送它,并在另一端对其进行解压缩以使用.将其压缩为文件不会解决我的问题.
outStream.Lentgh is much smaller than the uncompressed byte[], but after i try to read the MemoryStream my compressed byte[] just contains 0''s.
In the debuger I noticed that in outStream''s non public members _buffer is the expected size and contains bytes other than 0.
Am I doing something wrong reading the memory stream?
NOTE: I need to compress this array to send it over the wire and decompress it on the other side to work with. Compressing it to a file won''t solve my problem.
推荐答案
您的流在阅读时已结束.试试这个:
Your stream is at the end when you read it. Try this:
compressedCsvFile = new byte[outStream.Length];
if (outStream.CanSeek)
{
outStream.Seek(0, SeekOrigin.Begin);
}
outStream.Read(compressedCsvFile, 0, (int)outStream.Length);
由于内存流始终可以查找,因此您不需要进行CanSeek测试,但是值得进行此测试.
You shouldn''t need the CanSeek test since a memory stream can always seek, but it is worth including.
问题在于如何从内存流中获取数据.outStream.ToArray();
返回压缩的字节.
工作压缩方式:
The problem was getting the data out of the memory stream.outStream.ToArray();
returnes the compressed bytes.
Working Compression Method:
public static byte[] CompressData(string fileName)
{
byte[] uncompressedFileData = new byte[0];
byte[] compressedFileData = new byte[0];
try
{
var stopwatch = new Stopwatch();
stopwatch.Reset();
stopwatch.Start();
if (!File.Exists(fileName))
{
throw new FileNotFoundException(fileName + " not found");
}
uncompressedFileData = File.ReadAllBytes(fileName);
using (var outStream = new MemoryStream())
{
using (var compress = new DeflateStream(outStream, CompressionMode.Compress, true))
{
compress.Write(uncompressedFileData, 0, uncompressedFileData.Length);
compress.Flush();
compress.Close();
}
compressedFileData = outStream.ToArray();
}
stopwatch.Stop();
#if DEBUG
Console.WriteLine("Compressed {0} bytes to {1} bytes in {2} seconds", uncompressedFileData.Length, compressedFileData.Length, stopwatch.Elapsed.TotalSeconds);
#endif
}
catch (Exception ex)
{
m_Log.Error(ex.Message, ex);
}
return compressedFileData;
}
这篇关于使用DeflateStream压缩byte []时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!