Home
VB.NET
File Equals: Compare Files
Updated Jan 8, 2024
Dot Net Perls
File equals. Suppose you have two files on the disk, and want to determine if they have the same contents. How can this be done? In VB.NET, we can open and compare the files.
While the lengths of the files may be important, a file can have different contents than another but the same length. So we must compare all the bytes in the files.
File
Example. We include the System.IO namespace to ensure the File class, and its ReadAllBytes function can be accessed. We introduce a custom function, FileEquals.
Step 1 We call the FileEquals function on some files. Please change these paths to point to existing files on your hard disk.
Step 2 We read in the contents of the files. We use File.ReadAllBytes, which returns a Byte array containing the file contents.
Step 3 If the lengths of the arrays are equal, we must compare all individual bytes to be sure of equality.
Step 4 If a single byte is different in the two files, we return False, meaning the files are not equal.
Imports System.IO Module Module1 Function FileEquals(path1 As String, path2 As String) As Boolean ' Step 2: read in the contents of both files. Dim file1() As Byte = File.ReadAllBytes(path1) Dim file2() As Byte = File.ReadAllBytes(path2) ' Step 3: see if lengths are equal. If file1.Length = file2.Length ' Step 4: see if all bytes are equal. For i As Integer = 0 To file1.Length - 1 If file1(i) <> file2(i) Return False End If Next Return True End If Return False End Function Sub Main() ' Step 1: call FileEquals on some files. Dim result1 = FileEquals("programs/example.txt", "programs/example.txt") Dim result2 = FileEquals("programs/example2.txt", "programs/example.txt") Console.WriteLine(result1) Console.WriteLine(result2) End Sub End Module
True False
Some notes. It seems like there should be some way to tell if two files have the same contents, but checking all the bytes is necessary. Even a hash function must internally access all the bytes.
Summary. If two files are equal, we can sometimes avoid performing operations. This check can also be used to alert the user if something changed in an important file on the disk.
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 (new).
Home
Changes
© 2007-2025 Sam Allen