如何在 C# 中创建文件夹的哈希? [英] How do you create the hash of a folder in C#?

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

问题描述

我需要为包含一些文件的文件夹创建哈希.我已经为每个文件完成了这项任务,但我正在寻找一种方法来为文件夹中的所有文件创建一个哈希.关于如何做到这一点的任何想法?

I need to create the hash for a folder that contains some files. I've already done this task for each of the files, but I'm searching for a way to create one hash for all files in a folder. Any ideas on how to do that?

(当然我可以为每个文件创建散列并将其连接到一些大散列,但这不是我喜欢的方式)

(Of course I can create the 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();
}

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

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