VB.Net Program to Return the MDS Hash of a file

The below VB.net Console Application will simply return the MD5 hash of a file you pass to it as an argument.

Exmaple Usage:

“C:\test\File_MDS_Hash_Generator.exe” C:\Program Files (x86)\Microsoft Office\OFFICE11\EXCEL.EXE <enter>
3D478B8AF281FA52E8EF1BD9E7895DA5

Do NOT enclose the argument with quotes even if your path contains spaces or you will get an nasty error.

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileToHash As String
        Dim fileMD5 As String

        fileToHash = Command$()

        fileMD5 = GenerateFileMD5(fileToHash)

        Console.Write(fileMD5)
    End Sub

    Function GenerateFileMD5(ByVal filePath As String)
        Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
        Dim f As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)

        f = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
        md5.ComputeHash(f)
        f.Close()

        Dim hash As Byte() = md5.Hash
        Dim buff As StringBuilder = New StringBuilder
        Dim hashByte As Byte

        For Each hashByte In hash
            buff.Append(String.Format("{0:X2}", hashByte))
        Next

        Dim md5string As String
        md5string = buff.ToString()

        Return md5string
    End Function

End Module

 

2 thoughts on “VB.Net Program to Return the MDS Hash of a file”

  1.  

    Public Function MD5CalcFile(ByVal filepath As String) As String
            Using reader As New System.IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read)
                Using md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
                    Dim hash() As Byte = md5.ComputeHash(reader)
                    Return ByteArrayToString(hash)
                End Using
            End Using
        End Function
        Public Function ByteArrayToString(ByVal arrInput() As Byte) As String
            Dim sb As New System.Text.StringBuilder(arrInput.Length * 2)
            For i As Integer = 0 To arrInput.Length - 1
                sb.Append(arrInput(i).ToString("X2"))
            Next
            Return sb.ToString().ToLower
        End Function
    
    MD5CalcFile(path)
    Reply
  2. Is this line useful?
    f = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)

    I had to delete it because the read file was always in use after the function
    Without it the function works and the file is close correctly

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.