CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 372

372
Chương 9: File, thư mục, và I/O

using System.Security.Cryptography;

public class CompareFiles {

private static void Main(string[] args) {

if (args.Length != 2) {

Console.WriteLine("USAGE: CompareFiles [fileName] " +

[fileName]");

return;

}

Console.WriteLine("Comparing " + args[0] + " and " + args[1]);

// Tạo đối tượng băm.

HashAlgorithm hashAlg = HashAlgorithm.Create();

// Tính mã băm cho file thứ nhất.

FileStream fsA = new FileStream(args[0], FileMode.Open);

byte[] hashBytesA = hashAlg.ComputeHash(fsA);

fsA.Close();

// Tính mã băm cho file thứ hai.

FileStream fsB = new FileStream(args[1], FileMode.Open);

byte[] hashBytesB = hashAlg.ComputeHash(fsB);

fsB.Close();

// So sánh mã băm.

if (BitConverter.ToString(hashBytesA) ==

BitConverter.ToString(hashBytesB)) {

Console.WriteLine("Files match.");

}else {

Console.WriteLine("No match.");

}