Creating hash for folder

后端 未结 7 1140
梦谈多话
梦谈多话 2020-12-13 05:05

i need to create hash for folder, that contains some files. I already done this task for each of files, but i searching the way to create one hash for all files in folder.

相关标签:
7条回答
  • 2020-12-13 05:47

    This hashes all file (relative) paths and contents, and correctly handles file ordering.

    And it's quick - like 30ms for a 4MB directory.

    using System;
    using System.Text;
    using System.Security.Cryptography;
    using System.IO;
    using System.Linq;
    
    ...
    
    public static string CreateMd5ForFolder(string path)
    {
        // assuming you want to include nested folders
        var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
                             .OrderBy(p => p).ToList();
    
        MD5 md5 = MD5.Create();
    
        for(int i = 0; i < files.Count; i++)
        {
            string file = files[i];
    
            // hash path
            string relativePath = file.Substring(path.Length + 1);
            byte[] pathBytes = Encoding.UTF8.GetBytes(relativePath.ToLower());
            md5.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
    
            // hash contents
            byte[] contentBytes = File.ReadAllBytes(file);
            if (i == files.Count - 1)
                md5.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
            else
                md5.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
        }
    
        return BitConverter.ToString(md5.Hash).Replace("-", "").ToLower();
    }
    
    0 讨论(0)
提交回复
热议问题