8

使用 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 });

    }
4

2 回答 2

17

您可以使用该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));
于 2012-03-02T20:23:22.477 回答
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;
}
于 2016-04-28T22:29:15.093 回答