How to change the name of a NetworkAdapter in c#?

∥☆過路亽.° 提交于 2019-12-04 16:52:36

You can change the name of a NIC easily through the registry if you know how the registry structure works.

You will need the NetworkAdapters GUID in order to locate which path to open. To get the network adapter GUID I recommend first querying the WMI "Win32_NetworkAdapter" class. There is a GUID property along with all the other properties needed to identify specific adapters.

You will notice this GUID in the registry path: {4D36E972-E325-11CE-BFC1-08002BE10318}
Visit link for information on it: http://technet.microsoft.com/en-us/library/cc780532(v=ws.10).aspx

string fRegistryKey = string.Format(@"SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{0}\Connection", NIC_GUID);

RegistryKey RegistryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, @"\\" + Server.Name);

RegistryKey = RegistryKey.OpenSubKey(fRegistryKey, true); //true is for WriteAble.

RegistryKey.SetValue("Name", "<DesiredAdapterName>");

By design the windows UI will not allow for duplicate NIC names. However, you can force duplicate NIC names via the registry. We have done tests, there seem to be nothing critically effected by having duplicate names. Windows seems to still function fine. You just want to be wary about scripting against NIC names if you don’t incorporate anti-duplicate name logic.

To create uniqueness you can use the adapter index property associated with the WMI query.

You can also create a VB.NET dll with the functionality you need and reference and call it from your C# code.

Here is a console app demonstrating the code (I tested and it works :)

Option Explicit On
Module Module1
    Sub Main()

        Const NETWORK_CONNECTIONS = &H31&

        Dim sOldName = "Local Area Connection"
        Dim sNewName = "Network"

        Dim objShell, objFolder, colItems, objItem
        objShell = CreateObject("Shell.Application")
        objFolder = objShell.Namespace(NETWORK_CONNECTIONS)

        colItems = objFolder.Items
        For Each objItem In colItems
            Console.WriteLine(objItem.Name)
            If objItem.Name = sOldName Then
                objItem.Name = sNewName
            End If
            Console.WriteLine(objItem.Name)
        Next
    End Sub

End Module

It prints out:

Local Area Connection

Network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!