I have to take the directory of a file in zip file

僤鯓⒐⒋嵵緔 提交于 2021-01-29 02:05:37

问题


Can someone helps me out with my problem. I have to take a file's directory in zip file so i can calculate its MD5 hash (without unzip it). I am using DotNetZip Library but i can't find the solution of the problem. I'll show you what i've tryed and hope you will help as fast as possible. Thanks!

if (ofd.ShowDialog() == DialogResult.OK) 
{
    using (ZipFile zip = ZipFile.Read(ofd.FileName))
    {
        foreach (ZipEntry f in zip)
        {
            GetMD5HashFromFile(ofd.FileName+"\\"+f.FileName);
        }
    }
}

回答1:


The problem is that you do not extract the Zip entry, it is still in the archive. That is why it does not find the path. I recommend to use the stream and calculate on that, without extracting. Be aware of that MD5 is no collision safe.

You have to reference in your project the System.IO.Compression.FileSystem.dll. Full working console application:

public class Program
{

    static void Main(string[] args)
    {

        var z = ZipFile.OpenRead(@"C:\directory\anyfile.zip");
        foreach (ZipArchiveEntry f in z.Entries)
        {
           var yourhash = GetMD5HashFromFile(f.Open());
        }

    }

    public static string GetMD5HashFromFile(Stream stream)
    {
        using (var md5 = new MD5CryptoServiceProvider())
        {
            var buffer = md5.ComputeHash(stream);
            var sb = new StringBuilder();

            for (int i = 0; i < buffer.Length; i++)
            {
                sb.Append(buffer[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }


来源:https://stackoverflow.com/questions/32005757/i-have-to-take-the-directory-of-a-file-in-zip-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!