How to Calculate a Checksum in VB

How to Calculate a Checksum in VB thumbnail
Checksums check the integrity of a file on a computer.

The concept of a checksum was invented early in the history of computer science to verify the integrity of data. The most basic checksum is to calculate the sum of all the 1s and 0s that make up a file's data. That number can be stored separately. At a later date it can be calculated again to make sure the sum is the same. If it is, the file hasn't changed, and the integrity is intact. Modern checksums are much more complex, but for programmers writing in Visual Basic, the .NET framework provides checksum calculation capabilities out of the box.

Instructions

    • 1

      Copy and paste the following Imports statements into the top of the file containing the class with which you want to get the checksum:

      Imports System.IO
      Imports System.Security.Cryptography

    • 2

      Copy and paste the following function into the class body:

      Private Shared Function GetChecksum(file as String) as String
      Using stream as FileStream = File.OpenRead(file)
      Dim sha as SHA256Managed = New SHA256Managed()
      Dim checksum as byte[] = sha.ComputeHash(stream)
      Return BitConverter.ToString(checksum).Replace("-", String.Empty)
      End Using
      End Function

    • 3

      Call the checksum function with the following code:

      Dim checksumValue as String = YourClassName.GetChecksum("C:\path\to\file.ext")

Tips & Warnings

  • You can use the built-in .NET File Open Dialog control to make sure the user of your program selects a valid file path.

Related Searches:

References

Resources

  • Photo Credit file image by Byron Moore from Fotolia.com

Comments

You May Also Like

Related Ads

Featured