共用方式為


使用 Visual C# 建立 File-Compare 函式

本文提供如何在 Visual C# 中建立 File-Compare 函式的相關信息,並包含說明方法的程式代碼範例。

原始產品版本: Visual C#
原始 KB 編號: 320348

摘要

本文參照 Microsoft .NET Framework 類別庫命名空間 System.IO

本逐步解說文章示範如何比較兩個檔案,以查看其內容是否相同。 此比較會查看兩個檔案的內容,而不是檔名、位置、日期、時間或其他屬性。

這項功能類似於 MS-DOS 型 Fc.exe 公用程式,隨附於各種版本的 Microsoft Windows 和 Microsoft MS-DOS,以及一些開發工具。

本文所述的範例程式代碼會執行逐位元組比較,直到發現不相符或到達檔尾為止。 程式代碼也會執行兩個簡單的檢查,以提高比較的效率:

  • 如果兩個檔案參考都指向相同的檔案,則兩個檔案必須相等。
  • 如果兩個檔案的大小不同,這兩個檔案就不相同。

建立範例

  1. 建立新的 Visual C# Windows 應用程式專案。 根據預設,會建立 Form1。

  2. 將兩個文字框控件新增至表單。

  3. 將命令按鈕新增至表單。

  4. 在 [ 檢視] 功能表上,按兩下 [ 程序代碼]

  5. 將下列 using 語句新增至 Form1 類別:

    using System.IO;
    
  6. 將下列方法新增至 Form1 類別:

    // This method accepts two strings the represent two files to
    // compare. A return value of 0 indicates that the contents of the files
    // are the same. A return value of any other value indicates that the
    // files are not the same.
    private bool FileCompare(string file1, string file2)
    {
        int file1byte;
        int file2byte;
        FileStream fs1;
        FileStream fs2;
    
        // Determine if the same file was referenced two times.
        if (file1 == file2)
        {
            // Return true to indicate that the files are the same.
            return true;
        }
    
        // Open the two files.
        fs1 = new FileStream(file1, FileMode.Open);
        fs2 = new FileStream(file2, FileMode.Open);
    
        // Check the file sizes. If they are not the same, the files
        // are not the same.
        if (fs1.Length != fs2.Length)
        {
            // Close the file
            fs1.Close();
            fs2.Close();
    
            // Return false to indicate files are different
            return false;
        }
    
        // Read and compare a byte from each file until either a
        // non-matching set of bytes is found or until the end of
        // file1 is reached.
        do
        {
            // Read one byte from each file.
            file1byte = fs1.ReadByte();
            file2byte = fs2.ReadByte();
        }
        while ((file1byte == file2byte) && (file1byte != -1));
    
        // Close the files.
        fs1.Close();
        fs2.Close();
    
        // Return the success of the comparison. "file1byte" is
        // equal to "file2byte" at this point only if the files are
        // the same.
        return ((file1byte - file2byte) == 0);
    }
    
  7. 在命令按鈕的事件中貼上下列程式代碼 Click

    private void button1_Click(object sender, System.EventArgs e)
    {
        // Compare the two files that referenced in the textbox controls.
        if (FileCompare(this.textBox1.Text, this.textBox2.Text))
        {
            MessageBox.Show("Files are equal.");
        }
        else
        {
            MessageBox.Show("Files are not equal.");
        }
    }
    
  8. 儲存然後執行範例。

  9. 提供文字框中兩個檔案的完整路徑,然後按下命令按鈕。

參考資料

如需詳細資訊,請造訪 Microsoft 網站 System.IO 命名空間。