A Dutch software developer living in Chile
# Monday, August 03, 2009
How to get a SHA1 hash from a file in C#.Net

A simple way to get a hash code from a file:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Sha1
{
  class Program
  {
    static void Main(string[] args)
    {
      if (args.Length != 1)
      {
        Console.WriteLine("Usage: SHA1 <filename>");
        return;
      }

      string fileName = args[0];
      if (!File.Exists(fileName))
      {
        Console.WriteLine("File not found: {0}", fileName);
        return;
      }

      using (Stream s = File.OpenRead(fileName))
      {
        SHA1Managed sha = new SHA1Managed();
        byte[] result = sha.ComputeHash(s);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < result.Length; i++)
        {
          sb.AppendFormat("{0:x2}", result[i]);
        }
        Console.WriteLine("SHA1 Hash: {0}", sb);
      }

    }
  }
}


Monday, August 03, 2009 9:22:14 AM (Pacific SA Standard Time, UTC-04:00)  #    Comments [0]