gpt4 book ai didi

c# - ICSharpCode.SharpZipLib 验证 zip 文件

转载 作者:太空狗 更新时间:2023-10-29 19:58:41 27 4
gpt4 key购买 nike

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

}

最佳答案

您可以使用 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));

关于c# - ICSharpCode.SharpZipLib 验证 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9539730/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com