【问题标题】:Set IP address of a network interface useing c# and .Net API without WMI使用没有 WMI 的 c# 和 .Net API 设置网络接口的 IP 地址
【发布时间】:2019-01-25 13:06:00
【问题描述】:

我是 .Net 和 c# 编程的新手。 我正在尝试执行一个小程序来设置我的本地网卡的 IP 地址。 (我想要实现的是比通过 Windows 配置菜单更快) 所以我做了一些研究,发现了几个适合我需要的很好的例子。 无论如何,我已经意识到我可以通过 .Net 命名空间(System.Net.Networkinformation...)获取网络设备 IP 配置,但我不能设置一个新的(我的意思是,这个 API 充满了 getter 但没有setters) 所以,据我搜索,要设置 IP,我必须执行 WMI 调用。 我的问题是,是否有一种方法可以通过 .Net 来实现(我当时还没有找到)。 提前致谢!

【问题讨论】:

  • 你搜索过'c# WMI class'吗? C# WMI Tutorial
  • 不确定您对 via .Net 的含义。 System.Management 是框架的一部分。如果你不喜欢 WMI,有IPHelper,如果你更喜欢 API 调用,或者netsh,你更喜欢命令行控制台风格。
  • 你能发布你已经拥有的代码吗?
  • 有什么理由不能使用 WMI?
  • 现在使用 PowerShell 很常见,您可以轻松地从 C# 调用它。

标签: c# .net networking ip wmi


【解决方案1】:

您可以使用ORMi 库,因为它是一个 WMI 包装器,可让 WMI 访问更简单。

1) 定义你的类:

[WMIClass("Win32_NetworkAdapterConfiguration")]
public class NetworkAdapterConfiguration
{
    public int Index { get; set; } //YOU MUST SET THIS AS IT IS THE CIM_KEY OF THE CLASS
    public string Caption { get; set; }
    public string Description { get; set; }

    public uint IPConnectionMetric { get; set; }

    public UInt32 InterfaceIndex { get; set; }

    public string WINSScopeID { get; set; }

    public bool SetStatic(string ip, string netmask)
    {
        int retVal = WMIMethod.ExecuteMethod(this, new { IPAddress = new string[] { ip }, SubnetMask = new string[] { netmask } });

        if (retVal != 0)
            Console.WriteLine($"Failed to set network settings with error code {retVal}");

        return retVal == 0;
    }
}

2) 用途:

        WMIHelper helper = new WMIHelper("root\\CimV2");

        NetworkAdapterConfiguration networkInterface = helper.Query<NetworkAdapterConfiguration>().ToList()
            .Where(n => n.Description == "Intel(R) Ethernet Connection").SingleOrDefault();

        networkInterface.SetStatic("192.168.0.35", "255.255.255.0");

【讨论】:

  • 感谢代码示例!在 Windows 10 上运行,SetStatic 似乎被 EnableStatic 替换,而不是返回 int,而是返回一个具有 ReturnValue 属性的对象
猜你喜欢
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 2022-01-18
  • 1970-01-01
相关资源
最近更新 更多