我正在使用GZipStream来压缩/解压缩数据.我在DeflateStream上选择了这个,因为文档声明GZipStream还添加了一个CRC来检测损坏的数据,这是我想要的另一个功能.我的"正面"单元测试运行良好,我可以压缩一些数据,保存压缩的字节数组,然后再次成功解压缩.在.NET GZipStream压缩和解压问题后让我意识到我需要访问压缩或未压缩数据之前关闭GZipStream.
接下来,我继续写一个"负面"单元测试,以确保可以检测到损坏的数据.我之前使用MSDN中的GZipStream类的示例来压缩文件,使用文本编辑器打开压缩文件,更改一个字节以破坏它(好像用文本编辑器打开它还不够糟糕!),保存它然后解压缩它以确保我按预期得到了InvalidDataException.
当我编写单元测试时,我选择了一个任意字节来破坏(例如,compressedDataBytes [50] = 0x99)并得到一个InvalidDataException.到现在为止还挺好.我很好奇,所以我选择了另一个字节,但令我惊讶的是我没有得到例外.这可能没问题(例如,我巧合地命中了数据块中未使用的字节),只要数据仍然可以成功恢复.但是,我也没有得到正确的数据!
为了确保"它不是我",我从.NET GZipStream底部清除了代码压缩和解压缩问题,并将其修改为按顺序破坏压缩数据的每个字节,直到它无法正确解压缩.这是更改(请注意我使用的是Visual Studio 2010测试框架):
// successful compress / decompress example code from:
// https://stackoverflow.com/questions/1590846/net-gzipstream-compress-and-decompress-problem
[TestMethod]
public void Test_zipping_with_memorystream_and_corrupting_compressed_data()
{
const string sample = "This is a compression test of microsoft .net gzip compression method and decompression methods";
var encoding = new ASCIIEncoding();
var data = encoding.GetBytes(sample);
string sampleOut = null;
byte[] cmpData;
// Compress
using (var cmpStream = new MemoryStream())
{
using (var …Run Code Online (Sandbox Code Playgroud)