我在C#中使用DotNetZip从流中解压缩,如下所示:
public static void unzipFromStream(Stream stream, string outdir)
{ //omit try catch block
using (ZipFile zip = ZipFile.Read(stream)){
foreach (ZipEntry e in zip){
e.Extract(outdir, ExtractExistingFileAction.OverwriteSilently);
}
}
}
使用获得流
WebClient client = new WebClient();
Stream fs = client.OpenRead(url);
然而,我得到了以下异常
exception during extracting zip from stream System.NotSupportedException: This stream does not support seek operations.
at System.Net.ConnectStream.get_Position()
at Ionic.Zip.ZipFile.Read(Stream zipStream, TextWriter statusMessageWriter, Encoding encoding, EventHandler`1 readProgress)
在服务器端(ASP.NET MVC 4),返回FilePathResult
或FileStreamResult
都会导致此异常。
我应该在客户端以不同的方式获取流吗?或者如何让服务器返回一个"可查找"的流?谢谢
您必须将数据下载到文件或内存中,然后创建FileStream
或MemoryStream
,或其他支持查找的流类型。例如:
WebClient client = new WebClient();
client.DownloadFile(url, filename);
using (var fs = File.OpenRead(filename))
{
unzipFromStream(fs, outdir);
}
File.Delete(filename);
或者,如果数据适合内存:
byte[] data = client.DownloadData(url);
using (var fs = new MemoryStream(data))
{
unzipFromStream(fs, outdir);
}