Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

FileDiff2 Optimized

3.80/5 (3 votes)
13 Aug 2009CPOL 31.6K   163  
A file diff utility.

Introduction

This application is pretty basic, it uses FileStream objects to perform its task.

Using the code

C#
ASCIIEncoding Encode = new ASCIIEncoding();

// Open the files
//
FileStream streamA = File.OpenRead(args[0]);
FileStream streamB = File.OpenRead(args[1]);

// Get the stream length
// (so we don't have to caluculate this a million times)
//
long lenA = streamA.Length - 1;
long lenB = streamB.Length - 1;

// Read the bytes
//
int byteA;
int byteB;

do
{
    // Read the streams
    //
    byteA = streamA.ReadByte();
    byteB = streamB.ReadByte();

    // Are they the same
    //
    if (byteA != byteB)
    {
        // Remember where we parked the car
        //
        long startPos = streamB.Position;

        // Read streamB until we = StreamA
        //
        do
        {
            byteB = streamB.ReadByte();
        }
        while (byteA != byteB && streamB.Position <= lenB);

        // How long is the difference?
        //
        long length = streamB.Position - startPos;

        // Read the bytes
        //
        byte[] theseBytes = new byte[length];
        streamB.Seek(length * -1, SeekOrigin.Current);|
        streamB.Read(theseBytes, 0, (int)length);

        Console.WriteLine("Pos:{0}, Len:{1}, Str:{2}", startPos, 
                          length, Encode.GetString(theseBytes));
    }
}
while (streamA.Position <= lenA && streamB.Position <= lenB);

streamA.Close();
streamB.Close();

History

  • Aug 12, 2009: Written.
  • Aug 13, 2009: Rewritten to be more explicit, and I modified the file seeking and some variables to bring this down form 57ms run time to 27ms run time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)