Skip to content

Instantly share code, notes, and snippets.

@yutopio
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yutopio/187f1411089288aed9b3 to your computer and use it in GitHub Desktop.
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.
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