Monday, October 6, 2008

Get HardDrive serial number in .NET

This is my first post in this blog which is related to getting HardDrive serial number in .NET. Getting serial number of HardDrive in .NET application is very hot topic in developer community. Mostly developer needs HardDrive serial number to avoid piracy of windows based software as I have used this idea 3 yrs. back in my windows application.


In .NET, we can not get hardware information in depth as we were in C/C++. Because of this limitation we need to use C/C++ exe or dll in our .NET application.There are many ways to use non .NET dll in .NET applications. One of famous way is to create COM component in VC++ and use that COM in our .NET application but I have not used this way becuase I don't know how to create COM component in VC++. For sake of simplity of VC++ dll I had created simple API dll in VC++ and make API call through VB.NET application


To call API dll from VB.NET, we need to follow some specific steps. I have written those steps below:

  1. Put API dll in same folder where your application's exe reside.
  2. Add reference of System.Runtime.InteropServices in the class from where you wants call API function.
  3. Add <DllImport("API Dll Name")> attribute before function name which calls the API function. This function must be Shared.
  4. e.g.
  5. <DllImport("API Dll Name")> _
    Public Shared Function getHardDriveComputerID() As String
    End Function
    'Leave function empty - DLLImport attribute forces calls to function of API dll.
    Call getHardDriveComputerID() function from any class of your application as per your requirement.

In our case, I have used API dll named "Win32.dll" (I found this dll from googling) in my VB.NET application. This dll is works for following versions of Windows:

  • Windows 98
  • Windows 2000
  • Windows NT
  • Windows XP

Below compressed file contains sample application.



No comments: