计算文件的散列值

介绍一种使用md5计算hash值的方法。 下面的代码分别计算两个文件的散列值并比较两个文件是否相同。

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


        static bool fileCompare(string srcFilename, string destFilename)
        {
            try
            {
                //if file doesn't exist, will throw exception
                FileInfo srcFile = new FileInfo(srcFilename);
                FileInfo destFile = new FileInfo(destFilename);
                MD5 checksumCalculator = MD5.Create();
                byte[] srcChecksum = checksumCalculator.ComputeHash(srcFile.OpenRead());
                byte[] destChecksum = checksumCalculator.ComputeHash(destFile.OpenRead());
                if (srcChecksum.Length != destChecksum.Length)
                    return false;
                for (int index = 0; index < srcChecksum.Length; index++)
                {
                    if (srcChecksum[index] != destChecksum[index])
                        return false;
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return false;
        }
posted @ 2008-02-29 22:19  magicdlf  阅读(1007)  评论(0编辑  收藏  举报