From 9af2ff0faa96b3aafbf2d348b0eaf7bbeb0dff49 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Mon, 8 Dec 2014 18:21:19 +0000 Subject: [PATCH] added function to hash directory --- Saviour Backup System/tools.cs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/Saviour Backup System/tools.cs b/Saviour Backup System/tools.cs index e2b63ea..58fe991 100644 --- a/Saviour Backup System/tools.cs +++ b/Saviour Backup System/tools.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; +using System.Linq; +using System.IO; using System.Security.Cryptography; namespace Saviour_Backup_System @@ -34,5 +34,33 @@ namespace Saviour_Backup_System return sb.ToString(); } public static Int64 getUnixTimeStamp() { return (Int64)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } + + public static string hashDirectory(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(); + } } }