Home
VB.NET
File Equals: Compare Files
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 8, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.