Home
C#
File Equals: Compare Files
Updated Jan 8, 2024
Dot Net Perls
File equals. How can we determine if 2 files are equal? We can compare lengths, dates created and modified. But this is not always enough.
Equal contents. There is no way to know if the contents are the same unless we test them. We demonstrate a method that compares 2 files for equality.
File
Example. The simplest way to check 2 files for equal contents is to use File.ReadAllBytes on each file. Then we must compare the result arrays.
And If the arrays have the same length, each byte must be compared. If the arrays have different lengths, we know the files are not equal.
File.ReadAllBytes
Note The output of this program will depend on the contents of the two files. Please change the paths in Main().
using System;
using System.IO;

class Program
{
    static bool FileEquals(string path1, string path2)
    {
        byte[] file1 = File.ReadAllBytes(path1);
        byte[] file2 = File.ReadAllBytes(path2);
        if (file1.Length == file2.Length)
        {
            for (int i = 0; i < file1.Length; i++)
            {
                if (file1[i] != file2[i])
                {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    static void Main()
    {
        bool a = FileEquals("C:\\stage\\htmlmeta", "C:\\stage\\htmlmeta-aspnet");
        bool b = FileEquals("C:\\stage\\htmllink", "C:\\stage\\htmlmeta-aspnet");
        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}
True False
FileInfo note. If the common case in your program is that the files are not equal, then using a FileInfo struct and the Length property to compare lengths first would be faster.
File Size
FileInfo
Usage. Suppose we are trying to update a directory of files but some files may not be different. Instead of rewriting files, we can test them for equality first.
So If they are equal, we can just do nothing. Reading in a file is a lot faster than writing out a file.
Detail In this use case, this FileEquals method can significantly improve performance.
Summary. We can guess whether two files are equal by testing their dates and lengths. But we cannot know if every single byte is equal unless we test every single byte.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 8, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen