To comparetwo files byte by byte in C#, you can use FileStream or
File.ReadAllBytes for a full comparison. A more memory-efficient way is to stream the files and compare them block by block.
Example: Efficient Byte-by-Byte Comparison Using Streams
public static bool AreFilesIdentical(string filePath1, string filePath2)
{
const int bufferSize = 1024 * 1024; // 1 MB buffer
var fileInfo1 = new FileInfo(filePath1);
var fileInfo2 = new FileInfo(filePath2);
if (fileInfo1.Length != fileInfo2.Length)
return false;
using (var fs1 = new FileStream(filePath1, FileMode.Open, FileAccess.Read))
using (var fs2 = new FileStream(filePath2, FileMode.Open, FileAccess.Read))
{
var buffer1 = new byte[bufferSize];
var buffer2 = new byte[bufferSize];
int bytesRead1, bytesRead2;
do
{
bytesRead1 = fs1.Read(buffer1, 0, bufferSize);
bytesRead2 = fs2.Read(buffer2, 0, bufferSize);
if (bytesRead1 != bytesRead2)
return false;
for (int i = 0; i < bytesRead1; i++)
{
if (buffer1[i] != buffer2[i])
return false;
}
} while (bytesRead1 > 0);
}
return true;
}
Notes
This approach avoids loading entire files into memory, making it suitable for large files.
Comparing length first is a quick way to eliminate obviously unequal files.
A File.ReadAllBytes approach is simpler but less efficient for large files.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To compare two files byte by byte in C#, you can use
FileStreamorFile.ReadAllBytesfor a full comparison. A more memory-efficient way is to stream the files and compare them block by block.Example: Efficient Byte-by-Byte Comparison Using Streams
Notes
File.ReadAllBytesapproach is simpler but less efficient for large files.