C#-如何将静态IP地址设置为USB到以太网适配器?

C#-如何将静态IP地址设置为USB到以太网适配器?,c#,network-interface,C#,Network Interface,我有一个C#应用程序,其中我需要检测连接到PC的USB到以太网适配器,并将其设置为静态IP地址。适配器可以是任何品牌,我不知道最终用户会有哪一个。我只知道只有一个USB到以太网适配器连接到这台电脑 以下是我的当前代码,它本应有效: public static bool SetStaticIPAddress(out string exception) { const string USBtoEthernetAdapter = "USB to Ethernet Adapter";

我有一个C#应用程序,其中我需要检测连接到PC的USB到以太网适配器,并将其设置为静态IP地址。适配器可以是任何品牌,我不知道最终用户会有哪一个。我只知道只有一个USB到以太网适配器连接到这台电脑

以下是我的当前代码,它本应有效:

public static bool SetStaticIPAddress(out string exception)
{
    const string USBtoEthernetAdapter = "USB to Ethernet Adapter";

    var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
    var networkCollection = adapterConfig.GetInstances();
    foreach (ManagementObject adapter in networkCollection)
    {
        string description = adapter["Description"] as string;

        if (description.StartsWith(USBtoEthernetAdapter, StringComparison.InvariantCultureIgnoreCase))
        {
            try
            {
                var newAddress = adapter.GetMethodParameters("EnableStatic");
                newAddress["IPAddress"] = new string[] { "10.0.0.2"};
                newAddress["SubnetMask"] = new string[] { "255.255.255.0"};

                adapter.InvokeMethod("EnableStatic", newAddress, null);
                exception = null;
                return true;
            }
            catch (Exception ex)
            {
                exception = $"Unable to Set IP: {ex.Message}";
                return false;
            }
        }
    }
    exception = $"Could not find any \"{USBtoEthernetAdapter}\" device connected";
    return false;
}
但是,不幸的是,它没有,当我运行
ipconfig
时,IP没有设置为10.0.0.2,这使得我的应用程序中尝试
ping
的其他部分失败

当我调试代码时,我看到它确实找到了一个描述为“USB到以太网适配器”的
ManagementObject
,但它的IP没有改变

我在网上搜索并在MSDN上找到了这个使用
NetworkInterface
的代码示例,因此我尝试了以下方法:

NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
    IPInterfaceProperties properties = adapter.GetIPProperties();
    // This is the name of the USB adapter but I can't relay on this name
    // since I don't know which device the user will use except for the fact
    // that is will be a USB to Ethernet Adapter...
    if (adapter.Description == "Realtek USB FE Family Controller")
    {
        // No way to set the device IP here...
    }
}

是否有一种100%检测单个USB适配器并将其设置为静态IP的方法?

出于好奇。为什么要这样做。您是否使用管理权限运行此代码?改变网络接口的参数需要。我需要为工厂开发一个硬件测试软件,其中一个测试是以太网检查,因此,工厂将通过USB到以太网适配器将网络电缆从生产的硬件连接到PC,我需要设置硬件和PC的静态IP,然后对硬件执行
ping
。@Alejandro-是的,我是。安装我的软件需要管理员权限,但我没有在相关代码中对管理员进行特殊检查。@LiranFriedman但这段代码是安装的一部分吗?我很确定这个特定的代码片段需要管理员权限,不仅仅是在安装期间,因为它会更改全局系统配置。出于好奇,您可以将管理员权限检查添加到此特定部分吗。为什么要这样做。您是否使用管理权限运行此代码?改变网络接口的参数需要。我需要为工厂开发一个硬件测试软件,其中一个测试是以太网检查,因此,工厂将通过USB到以太网适配器将网络电缆从生产的硬件连接到PC,我需要设置硬件和PC的静态IP,然后对硬件执行
ping
。@Alejandro-是的,我是。安装我的软件需要管理员权限,但我没有在相关代码中对管理员进行特殊检查。@LiranFriedman但这段代码是安装的一部分吗?我很确定这个特定的代码片段需要管理员权限,不仅仅是在安装期间,因为它会更改全局系统配置。您可以将管理员权限检查添加到此特定部分吗?