Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created December 24, 2012 10:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atifaziz/4368761 to your computer and use it in GitHub Desktop.
Save atifaziz/4368761 to your computer and use it in GitHub Desktop.
C# program to compute MD5 hash of files specified as command-line arguments
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
static class Program
{
static void Run(IEnumerable<string> args)
{
args = from arg in args
select arg.Trim() into arg
where !string.IsNullOrEmpty(arg)
select arg;
if (!args.Any())
throw new Exception("Missing file path.");
foreach (var e in from path in args
select new
{
Path = Path.GetFullPath(path),
Hash = BitConverter.ToString(MD5Hash(path))
.ToLowerInvariant()
.Replace("-", string.Empty)
})
{
Console.WriteLine(e.Hash + " " + e.Path);
}
}
static byte[] MD5Hash(string path)
{
using (var stream = new FileStream(path, FileMode.Open,
FileAccess.Read,
FileShare.Read,
4096,
FileOptions.SequentialScan))
{
return MD5.Create().ComputeHash(stream);
}
}
static int Main(string[] args)
{
try
{
Run(args);
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Trace.TraceError(e.ToString());
return Environment.ExitCode != 0 ? Environment.ExitCode : 0xbad;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment