This post will discuss how to compare two files in C#.

1. Using FileStream.ReadByte() method

The idea here is to compare the given files byte-by-byte. The FileStream.ReadByte() method reads a byte from the file and advances the read position by one byte. This might be slow, but only a feasible performance-optimized solution for large files.

The following solution demonstrates the byte by byte comparison between two files. It reads data from a file, byte by byte, compares each byte for equality, and proceeds to the next byte.

Download Code

2. Using File.ReadAllBytes() method

When you are working with small files, you can read the entire contents of the file into a byte array using the File.ReadAllBytes() method, and check both byte arrays for equality using the Enumerable.SequenceEqual() method. This is the easiest solution for small files:

Download Code

3. Using File.ReadLines() method

Alternatively, you can use the File.ReadLines() method to read all the lines of the file into an IEnumerable<String>. This method can accept an encoding to use to read the file. Since it returns an enumerable, the whole file is not returned. The File.ReadAllBytes() method, on the other hand, returns the whole file as an array of strings.

Download Code

That’s all about comparing two files in C#.