ICSharpCode.SharpZipLib проверить zip-файл - PullRequest
7 голосов
/ 03 марта 2012

Используя ICSharpCode.SharpZipLib для C #, как я могу проверить, что передаваемый файл на самом деле является действительным 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 ]

15 голосов
/ 03 марта 2012

Вы можете использовать метод 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));
0 голосов
/ 29 апреля 2016

Будьте осторожны с этим. Это создало ошибку 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;
}
...