首页 > 技术文章 > [问题记录.dotnet]取网卡信息报错"找不到"-WMI - Not found

debug_fan 2016-03-24 11:46 原文

异常:

System.Management.ManagementException: 找不到 
   在 System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
   在 System.Management.ManagementObject.Initialize(Boolean getObject)
   在 System.Management.ManagementBaseObject.get_wbemObject()
   在 System.Management.ManagementBaseObject.get_ClassName()
   在 System.Management.ManagementClass.GetInstances(EnumerationOptions options)


现象:

某台机器之前使用正常,突然报这个错。
其他机器均正常。


解决:

1. 确保服务“Windows Management Instrumentation”开启。
2. 如果已经开启还是有问题,那么可能是WMI存储库损坏,需要重建WMI存储库。

要重建WMI存储库,(Win7等系统)步骤操作:
(如果是XP系统,参考 http://windowsxp.mvps.org/repairwmi.htm
————————————–

1.开始->所有程序->附件,以管理员身份打开命令提示符command
2.停止WMI服务:net stop winmgmt
3.Repository目录改名备份:ren %windir%\System32\Wbem\Repository Repository_backup
4.重启WMI服务:net start winmgmt
5.运行 winmgmt /salvagerepository 尝试重建Repository
6.注册WMI组件:
cd /d %windir%\system32\wbem
for /f %%s in (‘dir /b *.dll’) do regsvr32 /s %%s
for /f %%s in (‘dir /b *.mof *.mfl’) do mofcomp %%s
wmiprvse /regserver
winmgmt /regserver

7.重新启动系统

8.重新安装自动更新成功
—————————————–
如果仍不成功,运行 %SystemRoot%\System32\Wbem\WbemTest.exe 测试WMI连接,点击连接,再次点击连接。如果仍然有连接错误,那么需要尝试全面的重建,运行下面的命令:

rundll32.exe setupapi,InstallHinfSection WBEM 132 %windir%\inf\wbemoc.inf

执行上面的命令后,可能会需要读取 Windodws 7/Windows 2008 R2 安装盘。



分析:

导致错误的代码段
public static string GetNetworkCardInfo()
{ 
    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection moc2 = mc.GetInstances();  <span style="color:#ff0000;">//这一句抛出的异常</span>
    string netcard = string.Empty;
    foreach (ManagementObject mo in moc2)
    {
        if ((bool)mo["IPEnabled"] == true)
        {
            netcard = mo["MacAddress"].ToString();
            mo.Dispose();
            break;
        }
        mo.Dispose();
    }
    return netcard;
}
原因:
System.Management 命名空间下的方式基本都是依赖WMI (Windows Management Instrumentation) 服务的,所以自然就联想到WMI的问题。然后去用工具或vbs脚本检验一下,基本就能确认了。
 

推荐阅读