为什么ManagementObjectSearcher.Get()会引发UnauthorizedAccessException?
问题描述:
我正在开发一个.Net 4.6.1桌面应用程序,它使用以下代码来确定用于记录目的的人性化操作系统名称(如this answer中所建议的)。为什么ManagementObjectSearcher.Get()会引发UnauthorizedAccessException?
public static string GetOSFriendlyName()
{
string result = string.Empty;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem");
foreach (ManagementObject os in searcher.Get())
{
result = os["Caption"].ToString();
break;
}
return result;
}
不过,我从我的一些用户收到错误报告表明ManagementObjectSearcher.Get()
被抛出UnauthorizedAccessException
:
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Management.ThreadDispatch.Start()
at System.Management.ManagementScope.Initialize()
at System.Management.ManagementObjectSearcher.Initialize()
at System.Management.ManagementObjectSearcher.Get()
[my code]
我知道旁边没有关于WMI(有简单复制代码出来的上面的答案),所以我不知道什么可能会导致异常被抛出,我一直无法自己重现异常。谷歌搜索只会给那些试图远程连接到WMI的人带来结果,而我并没有(我不认为!)这样做。
什么可能会导致某些用户引发此异常而不引发其他用户?
答
确保用户具有正确的ACL,因为某些WMI查询需要提升权限才能执行。