C # how to determine whether the content of two files is the same

Source: Internet
Author: User

The hash algorithm generates a small binary "fingerprint" for a file. From a statistical perspective, different files cannot generate the same hash code.

To generate a hash code, you must first Create a HashAlgorithm object and use the HashAlgorithm. Create method. Then call

HashAlgorithm. ComputeHash method, which returns a byte array storing the hash code, and then uses BitConverter. Tostring ()

Replace it with a string for comparison.

The source code is as follows:

Copy codeThe Code is as follows: public static bool isValidFileContent (string filePath1, string filePath2)
{
// Create a hash algorithm object
Using (HashAlgorithm hash = HashAlgorithm. Create ())
{
Using (FileStream file1 = new FileStream (filePath1, FileMode. Open), file2 = new FileStream (filePath2, FileMode. Open ))
{
Byte [] hashByte1 = hash. ComputeHash (file1); // The hash algorithm obtains the byte array of the hash code based on the text.
Byte [] hashByte2 = hash. ComputeHash (file2 );
String str1 = BitConverter. ToString (hashByte1); // assemble the number of bytes into a string
String str2 = BitConverter. ToString (hashByte2 );
Return (str1 = str2); // compare the hash code
}
}
}

Main function that uses this function

Copy codeThe Code is as follows: static void Main (string [] args)
{
String filePath1 = @ "f:/1.txt ";
String filePath2 = @ "f:/2.txt ";
Bool valid = isValidFileContent (filePath1, filePath2 );
Console. WriteLine (valid. ToString ());
Console. ReadKey ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.