So sánh hai file trong C#



Bài tập C#: So sánh hai file

Viết chương trình C# để so sánh xem hai file có đồng nhất hay không (có cùng nội dung hay không).

Chương trình C#

Dưới đây là chương trình C# minh họa lời giải cho bài tập so sánh hai file trong C#. Bạn cần sử dụng System.IO namespace cho hoạt động đọc ghi file.

using System;
using System.IO;namespace VietJackCsharp
{
    class TestCsharp
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\nSo sanh hai file trong C#:");
            Console.WriteLine("--------------------------\n");
            bool equal = true;            FileStream myFile1;
            byte[] dataFile1;
            FileStream myFile2;
            byte[] dataFile2;            Console.Write("Nhap ten cua file1: ");
            string fileName1 = Console.ReadLine();            Console.Write("Nhap ten cua file2: ");
            string fileName2 = Console.ReadLine();            if ((!File.Exists(fileName1)) || (!File.Exists(fileName2)))
            {
                Console.WriteLine("File1 va File2 khong ton tai!!!");
                return;
            }            try
            {
                myFile1 = File.OpenRead(fileName1);
                dataFile1 = new byte[myFile1.Length];
                myFile1.Read(dataFile1, 0, (int)myFile1.Length);                myFile2 = File.OpenRead(fileName2);
                dataFile2 = new byte[myFile2.Length];
                myFile2.Read(dataFile2, 0, (int)myFile2.Length);                if (myFile1.Length == myFile2.Length) {
                    for (int i = 0; i < dataFile1.Length; i++) {
                        if (dataFile1[i] != dataFile2[i])
                        {
                            equal = false;
                        }
                        else {
                            equal = true;
                        }
                    }
                }
                if (equal)
                {
                    Console.WriteLine("{0} la dong nhat voi {1}", fileName1, fileName2);
                }
                else {
                    Console.WriteLine("{0} khong dong nhat {1}", fileName1, fileName2);
                }                Console.ReadLine();                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}!!!", e.Message);
            }
        }
    }
}

Nếu bạn không sử dụng lệnh Console.ReadKey(); thì chương trình sẽ chạy và kết thúc luôn (nhanh quá đến nỗi bạn không kịp nhìn kết quả). Lệnh này cho phép chúng ta nhìn kết quả một cách rõ ràng hơn.

Kết quả chương trình C#

Giả sử chúng ta có hai file: test.txttest2.txt có nội dung lần lượt như sau: (trong đó test2.txt là bản sao của test.txt trong bài tập trước)

So sánh hai file trong C# So sánh hai file trong C#

Biên dịch và chạy chương trình C# trên sẽ cho kết quả:

So sánh hai file trong C#
bai-tap-doc-ghi-file-trong-csharp.jsp