此文记录的是网卡操作的工具类。
/***
网卡工具类
Austin Liu 刘恒辉
Project Manager and Software Designer
Date: 2024-01-15 15:18:00
使用方法:
1、获取所有激活的网卡名称;
List<string> list = NetworkCardUtil.GetActivatedAdaptorNameList();
2、获取所有正在激活使用的网卡名称列表;
List<string> NewworkCardList = GetCurrentActiveatedNetworkCardList();
***/
namespace Lzhdim.LPF.Utility
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Management;
/// <summary>
/// 网卡工具类
/// </summary>
public class NetworkCardUtil
{
/// <summary>
/// 获得当前机器的活动网卡名称,如果列表元素为0则没联网
/// </summary>
/// <returns>网卡名称列表</returns>
public static List<string> GetActivatedAdaptorNameList()
{
List<string> list = new List<string>();
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (mo["IPEnabled"].ToString() == "True")
{
list.Add(mo["Description"].ToString());
}
}
return list;
}
/// <summary>
/// 获取当前正在联网使用的网卡名称列表
/// </summary>
/// <returns>网卡名称列表。如果元素为0则没有联网的网卡。</returns>
public static List<string> GetCurrentActiveatedNetworkCardList()
{
List<string> list = GetActivatedAdaptorNameList();
PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
List<string> NetworkCardList = new List<string>();
foreach (string name in category.GetInstanceNames())
{
// This one exists on every computer.
if (name == "MS TCP Loopback interface")
continue;
foreach (string item in list)
{
if (name.Replace('[', '(').Replace(']', ')') == item)
{
NetworkCardList.Add(name);
}
}
}
return NetworkCardList;
}
}
}