c# – 原始流有数据,Deflate返回零字节
发布时间:2020-12-15 21:15:50 所属栏目:百科 来源:网络整理
导读:我正在阅读数据(adCenter报告,因为它发生),它应该是压缩的.用普通的流读取内容,我得到几千字节的乱码,所以这似乎是合理的.所以我将流提供给DeflateStream. 首先,它报告“块长度与其补码不匹配”.简短的搜索表明存在一个双字节前缀,实际上如果我在打开Deflate
我正在阅读数据(adCenter报告,因为它发生),它应该是压缩的.用普通的流读取内容,我得到几千字节的乱码,所以这似乎是合理的.所以我将流提供给DeflateStream.
首先,它报告“块长度与其补码不匹配”.简短的搜索表明存在一个双字节前缀,实际上如果我在打开DeflateStream之前调用两次ReadByte(),则异常就会消失. 但是,DeflateStream现在根本不返回任何内容.我已经花了大半个时间在这上面追逐线索,没有运气.帮助我,StackOverflow,你是我唯一的希望!谁能告诉我我错过了什么? 这是代码.当然,我在测试时只启用了两个注释块中的一个. _results = new List<string[]>(); using (Stream compressed = response.GetResponseStream()) { // Skip the zlib prefix,which conflicts with the deflate specification compressed.ReadByte(); compressed.ReadByte(); // Reports reading 3,000-odd bytes,followed by random characters /*byte[] buffer = new byte[4096]; int bytesRead = compressed.Read(buffer,4096); Console.WriteLine("Read {0} bytes.",bytesRead.ToString("#,##0")); string content = Encoding.ASCII.GetString(buffer,bytesRead); Console.WriteLine(content);*/ using (DeflateStream decompressed = new DeflateStream(compressed,CompressionMode.Decompress)) { // Reports reading 0 bytes,and no output /*byte[] buffer = new byte[4096]; int bytesRead = decompressed.Read(buffer,4096); Console.WriteLine("Read {0} bytes.",##0")); string content = Encoding.ASCII.GetString(buffer,bytesRead); Console.WriteLine(content);*/ using (StreamReader reader = new StreamReader(decompressed)) while (reader.EndOfStream == false) _results.Add(reader.ReadLine().Split('t')); } } 正如您可能从最后一行猜测的那样,解压缩的内容应该是TDT. 只是为了好玩,我尝试用GZipStream解压缩,但它报告了幻数不正确. MS’文档只是说“下载的报告是使用zip压缩压缩的.您必须先解压缩报告才能使用其内容.” 这是最终有效的代码.我不得不将内容保存到文件中并将其重新读入.这似乎不合理,但对于我正在使用的少量数据,这是可以接受的,我会接受它! WebRequest request = HttpWebRequest.Create(reportURL); WebResponse response = request.GetResponse(); _results = new List<string[]>(); using (Stream compressed = response.GetResponseStream()) { // Save the content to a temporary location string zipFilePath = @"ServerFolderadCenterTemp.zip"; using (StreamWriter file = new StreamWriter(zipFilePath)) { compressed.CopyTo(file.BaseStream); file.Flush(); } // Get the first file from the temporary zip ZipFile zipFile = ZipFile.Read(zipFilePath); if (zipFile.Entries.Count > 1) throw new ApplicationException("Found " + zipFile.Entries.Count.ToString("#,##0") + " entries in the report; expected 1."); ZipEntry report = zipFile[0]; // Extract the data using (MemoryStream decompressed = new MemoryStream()) { report.Extract(decompressed); decompressed.Position = 0; // Note that the stream does NOT start at the beginning using (StreamReader reader = new StreamReader(decompressed)) while (reader.EndOfStream == false) _results.Add(reader.ReadLine().Split('t')); } } 解决方法
您会发现DeflateStream在解压缩的数据方面受到很大限制.事实上,如果您期望整个文件,它将毫无用处.
ZIP文件存在大量(大多数是小的)变体,而DeflateStream只会与其中的两个或三个相处. 最好的方法是使用专用库来读取Zip文件/流,如DotNetZip或SharpZipLib(有点不受维护). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |