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.
We include the System.IO
namespace to ensure the File class
, and its ReadAllBytes
function can be accessed. We introduce a custom function, FileEquals
.
FileEquals
function on some files. Please change these paths to point to existing files on your hard disk.File.ReadAllBytes
, which returns a Byte array containing the file contents.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 ModuleTrue False
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.
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.