C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
However: If the arrays have different lengths, we know the files are not equal.
File.ReadAllBytesNote: The output of this program will depend on the contents of the two files. Please change the paths in Main().
C# program that uses FileEquals
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);
}
}
Output
True
False
However: If the common case is that the files are equal, the above version would be faster, because the arrays are needed.
FileInfo LengthFileInfoSo: If they are equal, you can just do nothing. Reading in a file is a lot faster than writing out a file.
Therefore: In this use case, this FileEquals method can significantly improve performance.
And: Hash computations can give virtually unique file identifiers. But this is not advantageous here. We still need to read every byte.