我需要在保存之前检查文件是否已压缩。我创建了以下扩展方法来检查文件是否使用ZipFile
(来自SharpLibZip库)压缩:
public static bool IsCompressed(this HttpPostedFile postedFile)
{
Stream stream = postedFile.InputStream;
using (var zipFile = new ZipFile(stream))
{
return zipFile.TestArchive(true);
}
}
问题在于,当我调用HttpPostedFile.SaveAs()
时,它将文件保存为0kb:
if(uploadedFile.IsCompressed())
{
uploadedFile.InputStream.Seek(0, SeekOrigin.Begin);
uploadedFile.SaveAs(physicalZipFile.FullName);
}
这与在IsCompressed()
中使用流有关。我在尝试保存之前尝试过,但问题仍然存在。
有人可以在这里解释一下这个问题吗?
答案 0 :(得分:1)
对于任何偶然发现此事的人......这是我的解决方案:
使用ILSpy我反编译了程序集,发现ZipFile.Dispose()
实际上关闭了流。还有其他清理代码,所以我不建议不处理ZipFile
实例。
另一方面,ZipArchive
(System.IO.Compression
)实际上有以下重载的构造函数:
public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen)
将leaveOpen
设置为true
会在正确处理实例后让流保持打开状态。