Little and Mickle

All things are difficult before they are easy.

导航

File Comparer - To compare two files and check whether they have the same content

Since it is slow and has low performance to compare to files byte by byte, we could use MD5 algorithm to computer the Hash Code of the FileStream for specified files to check whether two files have the same content. .Net has MD5 algorithm inside, you can search MD5 in MSDN for detail.  You can download the full sample code and compiled program: https://files.cnblogs.com/davidullua/FileComparer.zip

Here's the sample code to compute hash code of a file:
        /// <summary>
        
/// to computer HashCode of a File, different files will generate different HashCode
        
/// </summary>
        
/// <param name="fileName"></param>
        
/// <returns></returns>

        public static string ComputeHashCode(string fileName)
        
{
            
if(!File.Exists(fileName))
            
{
                
throw new FileNotFoundException("File does not exist",fileName);
            }
            

            Stream fileStream 
= File.OpenRead(fileName); 
            
try 
            
{                
                MD5CryptoServiceProvider MD5Alg 
= new MD5CryptoServiceProvider(); 

                
byte[] hashValue = MD5Alg.ComputeHash(fileStream); 

                
return BitConverter.ToString(hashValue);                 
            }
 

            
catch 
            

                
throw
            }
 
            
finally 
            

                fileStream.Close();
            }
     
        }


Here's the code to compare two files' HashCode:
        /// <summary>
        
/// used to Compare Two files' HashCode, return true or false
        
/// </summary>
        
/// <param name="fileOne"></param>
        
/// <param name="fileTwo"></param>
        
/// <returns></returns>

        public static bool CompareFiles(string fileOne, string fileTwo) 
        
{
            
if(!File.Exists(fileOne) || !File.Exists(fileTwo))
            
{
                
throw new FileNotFoundException("File does not exist");
            }


            
try 
            
{  
                
string stringValue1 = ComputeHashCode(fileOne); 
                
string stringValue2 = ComputeHashCode(fileTwo);  

                
return (stringValue1.Equals(stringValue2)); 
            }
 

            
catch 
            

                
throw
            }
 


        }
 

posted on 2005-10-19 09:24  davidullua  阅读(529)  评论(0)    收藏  举报