System.DirectoryServices.AccountManagement.Principal.FindByIdentity中引发的异常

时间:2019-04-05 22:13:38

标签: c#

我正在尝试确定当前用户是否是本地Windows用户(而不是域用户)

这是我正在使用的代码,在大多数情况下它可以工作,但是在不属于域的某些Windows计算机上会抛出异常

bool localUser = false;
WindowsIdentity user = WindowsIdentity.GetCurrent();
SecurityIdentifier sid = user.User;
PrincipalContext pc = new PrincipalContext(ContextType.Machine);
using (Principal principal = Principal.FindByIdentity(pc, IdentityType.Sid, sid.ToString()))
{
    localUser = true;
}

这是例外,堆栈跟踪

System.InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.DirectoryServices.DirectoryEntry'.
   at System.DirectoryServices.AccountManagement.SAMStoreCtx.GetAsPrincipal(Object storeObject, Object discriminant)
   at System.DirectoryServices.AccountManagement.SAMStoreCtx.FindPrincipalByIdentRef(Type principalType, String urnScheme, String urnValue, DateTime referenceDate)
   at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
   at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, String identityValue)
   at System.DirectoryServices.AccountManagement.Principal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)````

0 个答案:

没有答案