创建文件夹哈希 [英] Creating hash for folder

查看:538
本文介绍了创建文件夹哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为文件夹中创建的哈希,包含一些文件。我已经完成了这个任务的每个文件,但我搜索创建文件夹中的所有文件中的一个哈希的方式。任何想法如何做到这一点?

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. Any ideas how to do that?

(当然我可以为每个文件创建哈希值,并将其串联到一些大的哈希值,但它不是一种方法,我喜欢)

(of course i can create hash for each file and concatenate it to some big hash but it's not a way i like)

先谢谢了。

推荐答案

本哈希的所有文件(相对)路径和,内容,正确处理文件排序

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

和它的快速 - 为4MB目录像30毫秒

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

这篇关于创建文件夹哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆