Solved

How to hash (MD5 or SHA1) a file with VB.NET

Posted on 2010-09-13
5
2,112 Views
Last Modified: 2012-05-10
Hi experts..
I have a VB.NET application which imports a few csv files into a database nightly..
I need to ascertain if the file has changed from the previous nights import before I decide to import it or not.

I thought the easiest way would be to hash the file and store this hash in a table.
Then, each subsequent nightly import, I would simply hash the file, compare it with the hash of the file uploaded the previous night, if the hash's match, do nothing, if the hash's are different, perform the import..

So, can anyone poiont me in the right direction for hashing a file with VB.NET please??

Thanks in advance.

D
0
Comment
Question by:jcm4101
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 29

Accepted Solution

by:
nffvrxqgrcfqvvc earned 500 total points
ID: 33668882
You can use HashAlgorithm Class, I wrote this class for when I need to calculate hash in either MD5 or SHA1 here you go.
The example defaults to MD5 but just change this line to use SHA1CryptoServiceProvider for SHA1 hash instead.
hashAlg = New MD5CryptoServiceProvider ' or New SHA1CryptoServiceProvider

Imports System.Security.Cryptography
Imports System.IO

Public Class FileChecksum
    Private Const BUF_SIZE As Integer = 65536
    ''' <summary>
    ''' Returns the file integrity checksum hash, otherwise an empty string.
    ''' </summary>
    Public Shared Function IntegrityCheck(ByVal filePath As String) As String
        Dim dataBuffer(BUF_SIZE - 1) As Byte
        Dim dataBufferDummy(BUF_SIZE - 1) As Byte
        Dim dataBytesRead As Integer = 0
        Dim hashResult As String = String.Empty
        Dim hashAlg As HashAlgorithm = Nothing
        Dim fs As FileStream = Nothing

        Try
            hashAlg = New MD5CryptoServiceProvider ' or New SHA1CryptoServiceProvider
            fs = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, BUF_SIZE)
            Do
                dataBytesRead = fs.Read(dataBuffer, 0, BUF_SIZE)
                hashAlg.TransformBlock(dataBuffer, 0, dataBytesRead, dataBufferDummy, 0)
            Loop Until dataBytesRead = 0
            hashAlg.TransformFinalBlock(dataBuffer, 0, 0)
            hashResult = BitConverter.ToString(hashAlg.Hash).Replace("-", "").ToLower
        Catch ex As IOException
            MsgBox(ex.Message, MsgBoxStyle.Critical, "IntegrityCheck")
        Catch ex As UnauthorizedAccessException
            MsgBox(ex.Message, MsgBoxStyle.Critical, "IntegrityCheck")
        Finally
            If Not fs Is Nothing Then
                fs.Close()
                fs.Dispose()
                fs = Nothing
            End If
            If Not hashAlg Is Nothing Then
                hashAlg.Clear() 'Dispose()
                hashAlg = Nothing
            End If
        End Try
        Return hashResult
    End Function

End Class

Open in new window

0
 

Author Closing Comment

by:jcm4101
ID: 33668977
Excellent work...
Thanks for the quick and complete solution.

D
0
 

Author Comment

by:jcm4101
ID: 33669031
Actually, I'm a bit confused...

What's the correct way to call this class??

Ta
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33669056
Whoops I forgot to show that part :(
It's basically just one shared method wrapped in class so it's similiar in respect to a module where you don't need to create an instance.
In the example below I used hashed the windows calculator on Windows 7: calc.exe MD5: 4884da7754823b44ccc2b2106f21146e
 

Debug.Print(FileChecksum.IntegrityCheck("c:\windows\system32\calc.exe"))

Open in new window

0
 

Author Comment

by:jcm4101
ID: 33669084
Thanks  a lot..

Just sussed it out myself too  :-)

Greatly appreciated.

D
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

626 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question