简体   繁体   English

如何从注册表设置或获取NetworkAddress项

[英]How to set or get the NetworkAddress key from the registry

I want to read and modify the registry key value of my NetworkAddress. 我想读取和修改我的NetworkAddress的注册表项值。 Its path in the registry is: 它在注册表中的路径是:

HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\Class{4D36E972-E325-11CE-BFC1-08002BE10318}\\0011 HKEY_LOCAL_MACHINE \\ SYSTEM \\ ControlSet001 \\控制\\类{4D36E972-E325-11CE-BFC1-08002BE10318} \\ 0011

Inside that path there is a key named NetworkAddress. 在该路径中有一个名为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. 请帮帮我,谢谢。

You are getting the exception because the factory method couldn't find the sub key at the specified location and returned null . 您将获得异常,因为工厂方法无法在指定位置找到子键并返回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. 尽管您的子密钥地址完全有效,但由于您使用的是Registry.LocalMachine.OpenSubKey ,因此您实际上是在子密钥地址中指定HKEY_LOCAL_MACHINE两次。 The solution is to change your sub-key path to: 解决方案是将子键路径更改为:

SYSTEM\\ControlSet001\\Control\\Class{4D36E972-E325-11CE-BFC1-08002BE10318}\\0011 SYSTEM \\ ControlSet001 \\控制\\类{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);
    }
}

C# is quite a rich language, so this is a lot easier to do without the registry C#是一种非常丰富的语言,所以没有注册表就可以轻松实现

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM