How does C determine if the contents of two files are the same
- 2020-05-10 18:42:10
- OfStack
The hash algorithm generates a small binary "fingerprint" for each file. From a statistical point of view, it is impossible for different files to generate the same hash code
To generate a hash code, you must first create an HashAlgorithm object through the HashAlgorithm.Create method. And then call
The HashAlgorithm.ComputeHash method returns a byte array that stores the hash code, and then USES BitConverter.Tostring () to store it
Replace it with a string for comparison.
The source code is as follows:
public static bool isValidFileContent(string filePath1, string filePath2)
{
// create 1 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 gets the byte array of the hash code from the text
byte[] hashByte2 = hash.ComputeHash(file2);
string str1 = BitConverter.ToString(hashByte1);// Replaces the byte assembly with a string
string str2 = BitConverter.ToString(hashByte2);
return (str1==str2);// Compare hash codes
}
}
}
The main function that USES this function
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();
}