CSharp .Net Tutorial: Comparing Files

James Cloud
If you are creating a File Manager, Drive Utility, or any other type of program that deals quite regularly with file operations you might find it useful to have a function that can compare to file and check to see if they have the save contents.

This tutorial will guide you through creating and using a function that compares two given files to see if their contents match and return a result.

Comparing Two Files

Before proceeding to the actual comparing functions creation you will first need to add a reference to System IO to the beginning of your namespace, like this:

using System.IO;

Once you have added the System IO reference to your project it is time to create the comparison function itself. First, create a public int function called Compare, with two String parameters called File1 and File2. Now use the code below to construct your function.

public int Compare(String File1, String File2)
{
int int1;
int int2;

int1 = 0;
int2 = 0;

FileStream myFile1;
FileStream myFile2;

try {
//Read the First File
try
{
myFile1 = new FileStream(File1, FileMode.Open);
}
catch {return 3;}

//Read the Second File
try
{
myFile2 = new FileStream(File2, FileMode.Open);
}
catch {return 3;}
}
catch {return 4;}

//Start Comparing the Two Files
try
{
do
{
int1 = myFile1.ReadByte();
int2 = myFile2.ReadByte();
if(int1 != int2) break;
} while(int1 != -1 && int2 != -1);
}
catch{}
//Check and Return the Results
if(int1 != int2)
{
myFile1.Close();
myFile2.Close();
return 0;
}
else
{
myFile1.Close();
myFile2.Close();
return 1;
}
}

The above function will return 1 if the files match, 2 if they differ, and 3 if they are not found.

Conclusion

Now, all you have to do is call the newly created Compare function supplying the path to the two files as parameters. For example:

if(Compare("C:\\myFile1.txt", "C:\\myFile2.txt") == 1)
{
MessageBox.Show("The Files Match");
}
else
{
MessageBox.Show("The Files Differ");
}

The example given above will compare C:\myFile1.txt to c:\myFile2.txt and if they match it will return 1 and show a message box saying, "The Files Match". If the two files fail to match the function will return 0 and show a message box saying, "The Files Differ".

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.