Last active
August 29, 2015 14:13
-
-
Save yutopio/187f1411089288aed9b3 to your computer and use it in GitHub Desktop.
Obtain MD5 file hash for all files in subdirectories in a specified path.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Security.Cryptography; | |
using System.Text; | |
static class Program | |
{ | |
static MD5 md5; | |
static MemoryStream ms; | |
static StreamWriter sw; | |
// Data directory to dump a hash. | |
const string path = @"F:\VPN"; | |
static void Main(string[] args) | |
{ | |
md5 = MD5.Create(); | |
ms = new MemoryStream(); | |
sw = new StreamWriter(ms); | |
var start = DateTime.Now; | |
Dump(new DirectoryInfo(path)); | |
var end = DateTime.Now; | |
var elapsed = end - start; | |
sw.Flush(); | |
ms.Seek(0, SeekOrigin.Begin); | |
var rootHash = ComputeHashForStream(ms); | |
Console.Error.WriteLine(); | |
Console.Error.WriteLine("Elapsed: {0}", elapsed); | |
Console.WriteLine("Root hash: {0}", rootHash); | |
} | |
static void Dump(DirectoryInfo dir) | |
{ | |
foreach (var d in dir.GetDirectories()) | |
{ | |
try { Dump(d); } | |
catch (UnauthorizedAccessException) { } | |
} | |
foreach (var f in dir.GetFiles()) | |
{ | |
using (var s = f.OpenRead()) | |
{ | |
Console.Error.WriteLine(f.FullName); | |
var hash = ComputeHashForStream(s); | |
var fileName = f.FullName.Replace(path, ""); | |
sw.WriteLine(hash); | |
Console.WriteLine("{0}\t{1}", hash, fileName); | |
} | |
} | |
} | |
static string ComputeHashForStream(Stream s) | |
{ | |
var hash = md5.ComputeHash(s); | |
var hashStr = Convert.ToBase64String(hash); | |
return hashStr.Substring(0, hashStr.Length - 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment