VB.NET - Compare Two Files



Compare Two Files


'Namespace: System.IO

Private Function CompareFiles(ByVal file1 As String, ByVal file2 As String) As Boolean
    'Set to true if the files are equal; false otherwise
    Dim filesAreEqual As Boolean = False

    With My.Computer.FileSystem
        ' Ensure that the files are the same length before comparing them line by line
        If .GetFileInfo(file1).Length = .GetFileInfo(file2).Length Then
            Using file1Reader As New FileStream(file1, FileMode.Open), _
                  file2Reader As New FileStream(file2, FileMode.Open)
                Dim byte1 As Integer = file1Reader.ReadByte()
                Dim byte2 As Integer = file2Reader.ReadByte()
                ' If byte1 or byte2 is a negative value, we have reached the end of the file
                While byte1 > 0 And byte2 > 0
                    If (byte1 <> byte2) Then
                        filesAreEqual = False
                        Exit While
                    Else
                        filesAreEqual = True
                    End If
                    'Read the next byte
                    byte1 = file1Reader.ReadByte()
                    byte2 = file2Reader.ReadByte()
                End While
            End Using
        End If
    End With

    Return filesAreEqual
End Function

Share |

 Cant find the page you are looking for?
 Help us to improve by adding the content that you are looking for.
 Leave a feedback
 We look forward to hear your comments and feedback.