Search code examples
c#zipdotnetzip

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


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

Solution

  • 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();
            }
        }