VB Magic

2013/06/24

VB.Net Getting a MD5 from a remote file asynchronously

Filed under: .NET, VB.NET — Tags: , , — vbmagic @ 3:10 pm

Took me a few hours to work this one out so I thought I’d post a small code snippet to show how it is done.

To do this you need the following Imports

Imports System.Net
Imports System.IO
Imports System.Security.Cryptography

It cheats in the fact that it downloads the file first and then does a checksum on it. But this is going to be used as a trigger for something else.

    Private _wc As New WebClient
    Private _baseUri As String = "http://mysite.com/myfiles/"

    Private Async Function GetDetails(filename As String) As Task(Of String)
        Await _wc.DownloadFileTaskAsync(New Uri(_baseUri & filename), "c:\downloads\" & filename)
        Dim result As String
        Using stream = New BufferedStream(File.OpenRead("c:\downloads\" & filename), 1200000)
            Dim hash As New MD5CryptoServiceProvider
            Dim checksum As Byte() = hash.ComputeHash(stream)
            result = BitConverter.ToString(checksum).Replace("-", String.Empty)
        End Using
        Return result
    End Function

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim md5 As String
        md5 = Await GetDetails("myfile.exe")
        ResultLabel.Text = md5
    End Sub

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: