Thursday, June 25, 2009

Local Machine - Registry & MAC Address

Recently, had a need to come up with a utility that deals with local machine info/settings, like getting name, MAC address, add/delete/get registry info. Wrote a handler (or utility) that does few things for me and here is a snippet that does the job.

One interesting thing out of it is to get MAC address and I know there are many ways people go about doing this; I chose to look for the first active network interface that has non zero in first 3 octets of the address. Well, the code isn't that complex and easy to look at - take a look:


using System;
using System.Net.NetworkInformation;
using Microsoft.Win32;

namespace MyCompany.MyProject
{
/// <summary>
/// Local Machine Handler
/// </summary>
public class LocalMachineHandler
{
public enum RegistryType
{
LocalMachine,
CurrentUser,
Users,
ClassesRoot,
CurrentConfig,
}

#region Private Properties
private static LocalMachineHandler _localMachineHandler = null;
#endregion Private Properties

#region Public Properties
/// <summary>
/// Singleton instance of LocalMachineHandler
/// </summary>
public static LocalMachineHandler Instance
{
get
{
if (_localMachineHandler == null)
_localMachineHandler = new LocalMachineHandler();
return _localMachineHandler;
}
}

/// <summary>
/// Gets currently loggedin User
/// </summary>
public string UserName
{
get
{
try { return System.Windows.Forms.SystemInformation.UserName; }
catch { return "All Users"; }
}
}

/// <summary>
/// Gets Computer Name
/// </summary>
public string ComputerName
{
get
{
try { return System.Windows.Forms.SystemInformation.ComputerName; }
catch { return ""; }
}
}

/// <summary>
/// Gets MAC Address of the computer
/// </summary>
public string MacAddress
{
get
{
string macAddress = "";
#region Logic to get MacAddress
try
{
IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

if (nics != null && nics.Length > 0)
{
// All network interfaces
string firstFewOctets = "";
int octetCount = 0;
foreach (NetworkInterface adapter in nics)
{
macAddress = "";
firstFewOctets = "";
octetCount = 0;
IPInterfaceProperties properties = adapter.GetIPProperties();
// Look for the first interface that is up
if (adapter.OperationalStatus == OperationalStatus.Up)
{
// Get the physical address and format
PhysicalAddress address = adapter.GetPhysicalAddress();
byte[] bytes = address.GetAddressBytes();
for (int i = 0; i < bytes.Length; i++)
{
octetCount += 1;
// Get the first 3 octets and make sure they all are not 0
if (octetCount < 4)
firstFewOctets += string.Format("{0}", bytes[i].ToString("X2"));
// Get the physical address in hexadecimal.
macAddress += string.Format("{0}", bytes[i].ToString("X2"));
// Insert a hyphen after each byte, unless we are at the end of the address.
if (i != bytes.Length - 1)
{
macAddress += "-";
}
}
// make sure it's not all 0
if (firstFewOctets != null &&
firstFewOctets.Trim() != null &&
firstFewOctets.Trim().Length > 0 &&
firstFewOctets.Replace("0", "").Length > 0)
break;
}
}
}
}
catch { } // Nothing to catch, it's ok not to get a MAC address
#endregion Logic to get MacAddress
return macAddress;
}
}
#endregion Public Properties

#region Constructors
/// <summary>
/// Singleton - therefore prvate constructor
/// </summary>
private LocalMachineHandler() { }
#endregion Constructors

#region Public Methods

#region Registry methods

/// <summary>
/// Gets Registry value for the type
/// </summary>
/// <param name="registryType"></param>
/// <param name="keyPath"></param>
/// <param name="valueName"></param>
/// <returns></returns>
public string GetRegistryValue(RegistryType registryType, string keyPath, string valueName)
{
try
{
// Based on the type of registry, Open
RegistryKey registryKey = null;
switch (registryType)
{
case RegistryType.ClassesRoot:
registryKey = Registry.ClassesRoot.OpenSubKey(keyPath);
break;
case RegistryType.CurrentConfig:
registryKey = Registry.CurrentConfig.OpenSubKey(keyPath);
break;
case RegistryType.CurrentUser:
registryKey = Registry.CurrentUser.OpenSubKey(keyPath);
break;
case RegistryType.LocalMachine:
registryKey = Registry.LocalMachine.OpenSubKey(keyPath);
break;
case RegistryType.Users:
registryKey = Registry.Users.OpenSubKey(keyPath);
break;
default:
registryKey = Registry.LocalMachine.OpenSubKey(keyPath);
break;
}
return registryKey.GetValue(valueName).ToString();
}
catch { return ""; }
}

/// <summary>
/// Adds Registry value for the type
/// </summary>
/// <param name="registryType"></param>
/// <param name="keyPath"></param>
/// <param name="valueName"></param>
/// <param name="valueData"></param>
/// <returns></returns>
public bool AddRegistry(RegistryType registryType, string keyPath, string valueName, string valueData)
{
try
{
// Based on the type of registry, create
RegistryKey registryKey = null;
switch (registryType)
{
case RegistryType.ClassesRoot:
registryKey = Registry.ClassesRoot.CreateSubKey(keyPath);
break;
case RegistryType.CurrentConfig:
registryKey = Registry.CurrentConfig.CreateSubKey(keyPath);
break;
case RegistryType.CurrentUser:
registryKey = Registry.CurrentUser.CreateSubKey(keyPath);
break;
case RegistryType.LocalMachine:
registryKey = Registry.LocalMachine.CreateSubKey(keyPath);
break;
case RegistryType.Users:
registryKey = Registry.Users.CreateSubKey(keyPath);
break;
default:
registryKey = Registry.LocalMachine.CreateSubKey(keyPath);
break;
}
registryKey.SetValue(valueName, valueData);
return true;
}
catch { return false; }
}

/// <summary>
/// Deletes a registry path
/// </summary>
/// <param name="registryType"></param>
/// <param name="keyPath"></param>
/// <returns></returns>
public bool DeleteRegistry(RegistryType registryType, string keyPath)
{
try
{
// Based on the type of registry, Delete
switch (registryType)
{
case RegistryType.ClassesRoot:
Registry.ClassesRoot.DeleteSubKey(keyPath);
break;
case RegistryType.CurrentConfig:
Registry.CurrentConfig.DeleteSubKey(keyPath);
break;
case RegistryType.CurrentUser:
Registry.CurrentUser.DeleteSubKey(keyPath);
break;
case RegistryType.LocalMachine:
Registry.LocalMachine.DeleteSubKey(keyPath);
break;
case RegistryType.Users:
Registry.Users.DeleteSubKey(keyPath);
break;
default:
Registry.LocalMachine.DeleteSubKey(keyPath);
break;
}
return true;
}
catch { return false; }
}

#endregion Registry methods

#endregion Public Methods
}
}


Love coding!

2 comments:

RRave said...

Dear Sir,

I have seen you are writing excellent articles in websites,Since i would like to invite to newly launched website for Programming resource site www.codegain.com. I hope you will join with us and contribute for us also.

Thank you
RRaveen

Mohamed Abdeen said...

dear sir,
it is very interesting blog i saw, but i am searching for function that can get the password of the administrator machine, can you help me in this?