ICSharpCode.SharpZipLib验证zip文件

时间:2012-03-02 20:12:06

标签: c# asp.net asp.net-mvc sharpziplib icsharpcode

对C#使用ICSharpCode.SharpZipLib,如何验证传递的文件实际上是否是一个有效的zip文件(不是右键单击并重命名为.zip)?

[HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
                if (fileData != null && fileData.ContentLength > 0)
                {
                    if (Path.GetExtension(fileData.FileName) == ".zip")
                    {
                        var zipFile = Server.MapPath("~/Content/uploads/" + Path.GetFileName(fileData.FileName));
                        fileData.SaveAs(zipFile);

                        FileStream fs = System.IO.File.OpenRead(zipFile);
                        ZipFile zf = new ZipFile(fs);

                        foreach (ZipEntry zipEntry in zf)
                        {
                            if (zipEntry.Name.EndsWith(".htm") || zipEntry.Name.EndsWith(".html"))
                            {
                                 return Json(new { success = true });                             
                            }
                        }
                        fs.Close();
                        fs.Dispose();
                        System.IO.File.Delete(zipFile);
                    }
                    else
                    {
                        var fileName = Server.MapPath("~/Content/uploads/" + Path.GetFileName(fileData.FileName));
                        fileData.SaveAs(fileName);                           
                        return Json(new { success = true });
                    }
                }                    
                return Json(new { success = false });

    }

2 个答案:

答案 0 :(得分:15)

您可以使用ZipFile.TestArchive方法。以下是SharpZipLib中声明的方式:

/// <summary>
/// Test an archive for integrity/validity
/// </summary>
/// <param name="testData">Perform low level data Crc check</param>
/// <returns>true if all tests pass, false otherwise</returns>
/// <remarks>Testing will terminate on the first error found.</remarks>
public bool TestArchive(bool testData)
{
    return TestArchive(testData, TestStrategy.FindFirstError, null);
}

用法示例:

ZipFile zipFile = new ZipFile("archive.zip");
Console.WriteLine("Archive validation result: {0}", zipFile.TestArchive(true));

答案 1 :(得分:0)

小心这个。当我立即尝试重命名时,它为我在文件上创建了一个IOAccess错误,我不得不添加一个using语句:

public static bool ValidateZipFile(string fileToTest)
{
    bool result;
    //Added using statement to fix IOAccess Blocking
    using (ICSharpCode.SharpZipLib.Zip.ZipFile zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(fileToTest))
    {
        result = zip.TestArchive(true, TestStrategy.FindFirstError, null);
    }
    return result;
}