我正在使用C#,并且正在Internet上下载其中包含一个XML文件的zip文件。我希望加载此XML文件。这是我到目前为止的内容:

byte[] data;
WebClient webClient = new WebClient();
try {
    data = webClient.DownloadData(downloadUrl);
}
catch (Exception ex) {
    Console.WriteLine("Error in DownloadData (Ex:{0})", ex.Message);
    throw;
}

if (data == null) {
    Console.WriteLine("Bulk data is null");
    throw new Exception("Bulk data is null");
}

//Create the stream
MemoryStream stream = new MemoryStream(data);
XmlDocument document = new XmlDocument();

//Gzip
GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress);

//Load report straight from the gzip stream
try {
    document.Load(gzipStream);
}
catch (Exception ex) {
    Console.WriteLine("Error in Load (Ex:{0})", ex.Message);
    throw;
}

document.Load中,我总是遇到以下异常:
GZip header 中的魔数(Magic Number)不正确。确保您正在传递GZip流。

我做错了什么?

最佳答案

我正在使用SharpZipLib,而且效果很好!

下面是封装库的函数

 public static void Compress(FileInfo sourceFile, string destinationFileName,string destinationTempFileName)
        {
            Crc32 crc = new Crc32();
            string zipFile = Path.Combine(sourceFile.Directory.FullName, destinationTempFileName);
            zipFile = Path.ChangeExtension(zipFile, ZIP_EXTENSION);

            using (FileStream fs = File.Create(zipFile))
            {
                using (ZipOutputStream zOut = new ZipOutputStream(fs))
                {
                    zOut.SetLevel(9);
                    ZipEntry entry = new ZipEntry(ZipEntry.CleanName(destinationFileName));

                    entry.DateTime = DateTime.Now;
                    entry.ZipFileIndex = 1;
                    entry.Size = sourceFile.Length;

                    using (FileStream sourceStream = sourceFile.OpenRead())
                    {
                        crc.Reset();
                        long len = sourceFile.Length;
                        byte[] buffer = new byte[bufferSize];
                        while (len > 0)
                        {
                            int readSoFar = sourceStream.Read(buffer, 0, buffer.Length);
                            crc.Update(buffer, 0, readSoFar);
                            len -= readSoFar;
                        }
                        entry.Crc = crc.Value;
                        zOut.PutNextEntry(entry);

                        len = sourceStream.Length;
                        sourceStream.Seek(0, SeekOrigin.Begin);
                        while (len > 0)
                        {
                            int readSoFar = sourceStream.Read(buffer, 0, buffer.Length);
                            zOut.Write(buffer, 0, readSoFar);
                            len -= readSoFar;
                        }
                    }
                    zOut.Finish();
                    zOut.Close();
                }
                fs.Close();
            }
        }

关于c# - 在C#中解压缩流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8212493/

10-09 21:23
查看更多