To check if two files are equal in C# and VB.NET you can use the following snippet.

Sample C#

public static bool FilesContentsAreEqual(FileInfo fileInfo1, FileInfo fileInfo2)
{
	bool result;

	if (fileInfo1.Length != fileInfo2.Length)
	{
		return false;
	}
	using (var file1 = fileInfo1.OpenRead())
	{
		using (var file2 = fileInfo2.OpenRead())
		{
			result = StreamsContentsAreEqual(file1, file2);
		}
	}
	return result;
}

public static bool StreamsContentsAreEqual(Stream stream1, Stream stream2)
{
	const int bufferSize = 2048 * 2;
	var buffer1 = new byte[bufferSize];
	var buffer2 = new byte[bufferSize];

	while (true)
	{
		var count1 = stream1.Read(buffer1, 0, bufferSize);
		var count2 = stream2.Read(buffer2, 0, bufferSize);

		if (count1 != count2)
		{
			return false;
		}

		if (count1 == 0)
		{
			return true;
		}

		var iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
		for (var i = 0; i < iterations; i++)
		{
			if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
			{
				return false;
			}
		}
	}
}

Sample VB.NET

Public Shared Function FilesContentsAreEqual(fileInfo1 As FileInfo, fileInfo2 As FileInfo) As Boolean
	Dim result As Boolean

	If fileInfo1.Length <> fileInfo2.Length Then
		Return False
	End If
	Using file1 = fileInfo1.OpenRead()
		Using file2 = fileInfo2.OpenRead()
			result = StreamsContentsAreEqual(file1, file2)
		End Using
	End Using
	Return result
End Function

Public Shared Function StreamsContentsAreEqual(stream1 As Stream, stream2 As Stream) As Boolean
	Const  bufferSize As Integer = 2048 * 2
	Dim buffer1 = New Byte(bufferSize - 1) {}
	Dim buffer2 = New Byte(bufferSize - 1) {}

	While True
		Dim count1 = stream1.Read(buffer1, 0, bufferSize)
		Dim count2 = stream2.Read(buffer2, 0, bufferSize)

		If count1 <> count2 Then
			Return False
		End If

		If count1 = 0 Then
			Return True
		End If

		Dim iterations = CInt(Math.Ceiling(CDbl(count1) / sizeof(Int64)))
		For i As var = 0 To iterations - 1
			If BitConverter.ToInt64(buffer1, i * sizeof(Int64)) <> BitConverter.ToInt64(buffer2, i * sizeof(Int64)) Then
				Return False
			End If
		Next
	End While
End Function

One thought on “How to check if two files are equal in C# and VB.NET”

Leave a Reply