摘要:[C#] 如何比較兩個檔案的內容是否完全相同
觀念:
一、如果傳遞給函式的兩個檔案的參考是指向相同的檔案,則這兩個檔案一定相同。
二、如果兩個檔案的大小不相同的話,則這兩個檔案內容一定不相同。
程式碼如下:
private void btnSelectFirstFile_Click(object sender, EventArgs e)
{
// 建立 OpenFileDialog 物件。
OpenFileDialog myOpenFileDialog = new OpenFileDialog();
// 設定 OpenFileDialog 物件的各個屬性。
myOpenFileDialog.CheckFileExists = true;
myOpenFileDialog.Title = "請選取第一個檔案";
myOpenFileDialog.InitialDirectory = "C:\\";
myOpenFileDialog.RestoreDirectory = true;
myOpenFileDialog.Multiselect = false;
// 將使用者所選取之文字檔的完整路徑顯示於 TextBox1 文字方塊中。
if(myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
TextBox1.Text = myOpenFileDialog.FileName;
}
}
private void btnSelectSecondFile_Click(object sender, EventArgs e)
{
// 建立 OpenFileDialog 物件。
OpenFileDialog myOpenFileDialog = new OpenFileDialog();
// 設定 OpenFileDialog 物件的各個屬性。
myOpenFileDialog.CheckFileExists = true;
myOpenFileDialog.Title = "請選取第二個檔案";
myOpenFileDialog.InitialDirectory = "C:\\";
myOpenFileDialog.RestoreDirectory = true;
myOpenFileDialog.Multiselect = false;
// 將使用者所選取之文字檔的完整路徑顯示於 TextBox2 文字方塊中。
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
TextBox2.Text = myOpenFileDialog.FileName;
}
}
private void btnGoToCompare_Click(object sender, EventArgs e)
{
if(FileCompare(this.TextBox1.Text, this.TextBox2.Text))
{
MessageBox.Show("兩個檔案是相同的。");
}
else
{
MessageBox.Show("兩個檔案並不相同。");
}
}
// 此方法所接收的兩個字串代表您所要比較的兩個檔案。
// 如果兩個檔案的內容完全相同,將傳回 True;任何其他
// 的傳回值都表示這兩個檔案的內容有所差異。
private bool FileCompare(string file1, string file2)
{
// 判斷相同的檔案是否被參考兩次。
if(file1 == file2)
{
return true;
}
int file1byte = 0;
int file2byte = 0;
using(FileStream fs1 = new FileStream(file1, FileMode.Open), fs2 = new FileStream(file2, FileMode.Open))
{
// 檢查檔案大小。如果兩個檔案的大小並不相同,則視為不相同。
if(fs1.Length != fs2.Length)
{
// 關閉檔案。
fs1.Close();
fs2.Close();
return false;
}
// 逐一比較兩個檔案的每一個位元組,直到發現不相符或已到達檔案尾端為止。
do
{
// 從每一個檔案讀取一個位元組。
file1byte = fs1.ReadByte();
file2byte = fs2.ReadByte();
}
while ((file1byte == file2byte) && (file1byte != -1));
// 關閉檔案。
fs1.Close();
fs2.Close();
}
// 傳回比較的結果。在這個時候,只有當兩個檔案
// 的內容完全相同時,"file1byte" 才會等於 "file2byte"。
return ((file1byte - file2byte) == 0);
} |
原文參考章立民研究室
(FileCompare)
三小俠 小弟獻醜,歡迎指教