Tuesday, August 19, 2008

How to get Windows’ Serial Number and Windows Logon User Name in .NET

By using the namespace System.Management, we can easily retrieve the serial number of your Windows OS and windows logon user name.

First of all, you need to add a reference of System.Management into your application. To add a reference into your .NET application, you can right-click on References in the solution explorer and select Add Reference.


From the Add References dialog box, select System.Management and click OK.


The sample codes below written in both C# and VB .NET show you how to read the Windows’ serial number and logon user name.

C# .NET
using System.Management;

public static string getSerialNumber() {
  string _serialNo = string.Empty;

  ManagementObjectSearcher objMOS = new ManagementObjectSearcher("Select * from Win32_OperatingSystem");
  ManagementObjectCollection objMOC;

  objMOC = objMOS.Get();

  foreach (ManagementObject objMO in objMOC) {
    _serialNo = objMO["SerialNumber"].ToString();
  }

  return _serialNo;
}

public static string getlogonUser(){
  string _user = string.Empty;

  ManagementObjectSearcher objMOS = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
  ManagementObjectCollection objMOC;

  objMOC = objMOS.Get();

  foreach (ManagementObject objMO in objMOC) {
    _user = objMO ["UserName"].ToString();
  }

  return _user;
}



VB .NET
Imports System.Management

Public Shared Function getSerialNumber() As String
  Dim _serialNo As String = String.Empty

  Dim objMOS As New ManagementObjectSearcher("Select * from Win32_OperatingSystem")
  Dim objMOC As ManagementObjectCollection

  objMOC = objMOS.Get

  For Each objMO As ManagementObject In objMOC
    _serialNo = objMO("SerialNumber").ToString()
  Next

  Return _serialNo
End Function

Public Shared Function getlogonUser() As String
  Dim _user As String = String.Empty

  Dim objMOS As New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
  Dim objMOC As ManagementObjectCollection

  objMOC = objMOS.Get

  For Each objMO As ManagementObject In objMOC
    _user = objMO("UserName").ToString()
  Next

  Return _user
End Function


Cheers.

1 comments:

hanuman on April 9, 2010 at 11:34 PM said...

Please solve this error
System.Security.Permissions.SecurityPermission
it is very urgent

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template