文件生成唯一的Hash码

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
public class MyClass
{
 public static void RunSnippet()
 {
  string path="E://EPMS0330//delete.log";
  string code=MyClass.CreateHash(path); 
  WL(path+" = "+code);
  
  WL("");
   path="E:/EPMS0330/EPMS.Web.IPPWP/UploadFiles/2010/4/16/291a6a97-5d70-4bd8-a282-66558d53d3ba.txt";
      code=MyClass.CreateHash(path); 
  WL(path+" = "+code);
  
  WL("");
   path="E:/EPMS0330/EPMS.Web.IPPWP/UploadFiles/2010/4/16/Tulips.jpg";
      code=MyClass.CreateHash(path); 
  WL(path+" = "+code);
 }
 public static string CreateHash(string fileName)
 {
  using (HashAlgorithm hashAlg = HashAlgorithm.Create())
  {
   using (FileStream fs = new FileStream(fileName, FileMode.Open))
   {
    byte[] hashBytes = hashAlg.ComputeHash(fs);
    string hash = "";
    foreach (byte bit in hashBytes)
    {
     hash = hash + bit;
    }
    return hash;
   }
  }
 }
 
 #region Helper methods
 
 public static void Main()
 {
  try
  {
   RunSnippet();
  }
  catch (Exception e)
  {
   string error = string.Format("---/nThe following error occurred while executing the snippet:/n{0}/n---", e.ToString());
   Console.WriteLine(error);
  }
  finally
  {
   Console.Write("Press any key to continue...");
   Console.ReadKey();
  }
 }

 private static void WL(object text, params object[] args)
 {
  Console.WriteLine(text.ToString(), args); 
 }
 
 private static void RL()
 {
  Console.ReadLine(); 
 }
 
 private static void Break()
 {
  System.Diagnostics.Debugger.Break();
 }

 #endregion
}

posted on 2010-06-18 16:51  xrt2004  阅读(1515)  评论(0编辑  收藏  举报

导航