compare 2 files

  • Thread starter Thread starter kids_pro
  • Start date Start date
K

kids_pro

What is the best method for comparing 2 file?
I want to create a utilities to syncronize 2 folders that perform function
similiar to robocopy.exe

Thanks,
kids
 
kids_pro said:
What is the best method for comparing 2 file?
I want to create a utilities to syncronize 2 folders that perform function
similiar to robocopy.exe

Do you just want to know if they're different or not?

If so, I suggest opening streams for both files, reading chunks at a
time and comparing them byte by byte. Note that you may not read the
same size of chunk each time - you basically want to read the next
chunk from a file when you've finished with the last chunk. Let me know
if you'd like some sample code for this.
 
kids_pro said:
Yes I do need some guiding code.
I found one sample they use MD5 to compare 2 files.
They open fileStream and then computeHash from the stream.
But I am not sure if this is the best method or not and does this method
ensure that 2 file are the sample by that.

Here's some code which I haven't tested *very* extensively, but is
pretty simple and should work. Note that it doesn't test the length of
the streams to start with, as not all streams support length tests. If
you know that yours do, you should do a length test to start with for
efficiency.

const int BufferLength = 32768;
static bool CompareStreams (Stream s1, Stream s2)
{
if (s1==null || s2==null)
{
throw new ArgumentNullException
("Streams to compare must both be non-null");
}

// A buffer for each stream
byte[] buffer1 = new byte[BufferLength];
byte[] buffer2 = new byte[BufferLength];

// Number of bytes valid within each buffer
int buffer1Valid=0;
int buffer2Valid=0;

// Index within the buffer for each stream
int buffer1Index=0;
int buffer2Index=0;

while (true)
{
// Read any more data if we need to
if (buffer1Index==buffer1Valid)
{
buffer1Valid = s1.Read(buffer1, 0, BufferLength);
buffer1Index=0;
}

if (buffer2Index==buffer2Valid)
{
buffer2Valid = s2.Read(buffer2, 0, BufferLength);
buffer2Index=0;
}

// We've read to the end of both streams simultaneously
if (buffer1Valid==0 && buffer2Valid==0)
{
return true;
}

// We've read to the end of one stream but not the other
if (buffer1Valid==0 || buffer2Valid==0)
{
return false;
}

if (buffer1[buffer1Index] != buffer2[buffer2Index])
{
return false;
}

buffer1Index++;
buffer2Index++;
}
}
 
Back
Top