In fact, the main purpose of writing this function is to demonstrate how to perform a byte-by-byte comparison operation until a match is found or the end of the file is reached. Our program code performs the following two simple checks to improve the efficiency of the comparison:
If the two file references that are passed to the function point to the same file, the two files must be the same, and there is no need to further compare the contents of the file.
If the size of the two files is different, the contents of these two files must be different, and there is no need to further compare the contents of the files.
Figure 1-34
Figure 1-34 shows the execution screen of the program example CH1_DEMOFORM044CS, which demonstrates how to use the Filecompare function we have written to compare the contents of two files to be identical. The program code is listed here as follows:
private void Btngotocompare_click (Object Sender,eventargs e)
{
If Filecompare (this. Textbox1.text,this.textbox2.text))
{
MessageBox.Show (two files are the same. ");
}
Else
{
MessageBox.Show (" Two files are not the same.
}
//The two strings received by this method represent the two files that you want to compare. If the contents of two files are identical,
returns True; any other
//return value indicates a difference in the contents of these two files.
Private bool Filecompare (string file1,string file2)
{
//Determine whether the same file is referenced two times.
if (file1 = file2)
{
return true;
}
int file1byte = 0;
int file2byte = 0;
using (FileStream FS 1 = new FileStream (file1,filemode.open),
FS2 = new FileStream (file2,filemode.open))
{
//check file size. If the size of the two files is not the same, it is considered different.
if (fs1length!= fs2. Length)
{
///close the file.
FS1. Close ();
FS2. Close ();
return False
}
//Compare each byte of two files until it is found that it does not match or has reached the end of the file.
do
{
//reads one byte from each file.
File1byte = FS1. ReadByte ();
File2byte = fs2. ReadByte ();
}
while (file1byte = = file2byte) && (file1byte!=-1);
//Closes the file.
FS1. Close ();
FS2. Close ();
}
//Returns the result of the comparison. At this point, the
File1byte equals "File2byte" only if the contents of the two files are exactly the same.
Return ((file1byte-file2byte) = = 0);