Reputation: 1785
I want to read and modify the registry key value of my NetworkAddress. Its path in the registry is:
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class{4D36E972-E325-11CE-BFC1-08002BE10318}\0011
Inside that path there is a key named NetworkAddress. How do I read and modify this key?
Here is what I have tried:
RegistryKey myKey = Registry.LocalMachine.OpenSubKey(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0011",true);
MessageBox.Show((string) myKey.GetValue("NetworkAddress"));
myKey.SetValue("NetworkAddress", "002408B2A2D2", RegistryValueKind.String);
I have tried this code and it is giving me this exception: Object reference not set to an instance of an object. How do I solve this issue? Please help me and thank you.
Upvotes: 1
Views: 3649
Reputation: 2180
C# is quite a rich language, so this is a lot easier to do without the registry
using System.Net.NetworkInformation;
var local = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.Name == "Local Area Connection").FirstOrDefault();
var stringAddress = local.GetIPProperties().UnicastAddresses[0].Address.ToString();
var ipAddress = IPAddress.Parse(address);
Upvotes: 1
Reputation: 7804
You are getting the exception because the factory method couldn't find the sub key at the specified location and returned null
.
Despite your sub key address being perfectly valid, because you are using Registry.LocalMachine.OpenSubKey
you are essentially specifying HKEY_LOCAL_MACHINE
in the sub key address twice. The solution is to change your sub-key path to:
SYSTEM\ControlSet001\Control\Class{4D36E972-E325-11CE-BFC1-08002BE10318}\0011
You may also want to consider a more robust approach:
using (RegistryKey myKey =
Registry.LocalMachine.OpenSubKey(
@"SYSTEM\ControlSet001\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0011", true))
{
if (myKey != null)
{
Console.WriteLine((string) myKey.GetValue("NetworkAddress"));
myKey.SetValue("NetworkAddress", "002408B2A2D2", RegistryValueKind.String);
}
}
Upvotes: 2