This blog is moved to
http://amalhashim.wordpress.com

Friday, March 13, 2009

Check whether two files are different or not

static public bool FilesDiffer(string filePath1, string filePath2)
{
if (new FileInfo(filePath1).Length != new FileInfo(filePath2).Length)
{
return true;
}

const int BUFFER_SIZE = 1024 * 1024;

byte[] buffer1 = new byte[BUFFER_SIZE];
byte[] buffer2 = new byte[BUFFER_SIZE];

using (FileStream file1 = File.OpenRead(filePath1))
using (FileStream file2 = File.OpenRead(filePath2))
{
while (true)
{
int n1 = file1.Read(buffer1, 0, BUFFER_SIZE);
int n2 = file2.Read(buffer2, 0, BUFFER_SIZE);

Debug.Assert(n1 == n2); // Files are supposed to be the same length!

if (n1 == 0) // End of file?
{
return false;
}

for (int i = 0; i < n1; ++i)
{
if (buffer1[i] != buffer2[i])
{
return true;
}
}
}
}
}

No comments: