Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Created December 13, 2015 13:22
Show Gist options
  • Select an option

  • Save ctigeek/9b2c4026ac6d13849ced to your computer and use it in GitHub Desktop.

Select an option

Save ctigeek/9b2c4026ac6d13849ced to your computer and use it in GitHub Desktop.
Create a hash for all files in a directory, including file content, name, and path.
public static byte[] GetDirectoryHash(string path)
{
var fileCount = 0;
var fileHasher = SHA1Managed.Create();
var sumHasher = SHA1Managed.Create();
sumHasher.Initialize();
var sw = new Stopwatch();
sw.Start();
foreach (var file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
using (var str = File.OpenRead(file))
{
var hash = fileHasher.ComputeHash(str);
sumHasher.TransformBlock(hash, 0, hash.Length, null, 0);
//hash the name and path of the file...
var filePath = Encoding.UTF8.GetBytes(file);
sumHasher.TransformBlock(filePath, 0, filePath.Length, null, 0);
fileCount++;
}
}
sumHasher.TransformFinalBlock(new byte[0], 0, 0);
sw.Stop();
Console.WriteLine("Hashed {0} files in {1} milliseconds.", fileCount, sw.ElapsedMilliseconds);
return sumHasher.Hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment