我需要知道我的windows currentuser是域用户还是本地用户? 我得到了我的CurrentPrincipal:
System.Threading.Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
答案 0 :(得分:4)
通常,Windows NON域用户没有UPN名称。如下所示如果我用/ upn发射WHOAMI:
C:\>WHOAMI /UPN
ERROR: Unable to get User Principal Name (UPN) as the current logged-on user
is not a domain user.
基于此使用以下代码,我们可以找到用户是否是域用户。
var upnName = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;
if (upnName == null)
{
//not a domain user
}
另一种冗长的方法是以SAM格式获取用户名。然后使用DirectoryEntry,DirectorySearcher和其他AD API迭代机器的所有连接域,并查找用户是否在我们迭代的任何域中。
Here is How to get domain user information from Active Directory in C#
答案 1 :(得分:0)
我没有AD,但我希望这可能有用:
public bool IsDomainUser()
{
bool isDomain = false;
foreach (var grp in WindowsIdentity.GetCurrent().Groups)
{
if (grp.IsValidTargetType(typeof(SecurityIdentifier)))
{
SecurityIdentifier si =
(SecurityIdentifier)grp.Translate(typeof(SecurityIdentifier));
// not sure if this is right, but I'm not in a domain and don't have this SID
// I do have LocalSID however, so you might need to turn it around,
// if you have LocalSid you are not using a domain acount
if (si.IsWellKnown(WellKnownSidType.BuiltinDomainSid))
{
isDomain = true;
}
}
}
return isDomain;
}
// for debugging list SIDS for current user and its groups
foreach (var obj in Enum.GetValues(typeof(WellKnownSidType)))
{
if (WindowsIdentity.GetCurrent().User.IsWellKnown((WellKnownSidType)obj))
{
Debug.WriteLine("User:" + obj.ToString());
}
foreach (var grp in WindowsIdentity.GetCurrent().Groups)
{
if (grp.IsValidTargetType(typeof(SecurityIdentifier)))
{
SecurityIdentifier si =
(SecurityIdentifier) grp.Translate(typeof(SecurityIdentifier));
if (si.IsWellKnown((WellKnownSidType)obj))
{
Debug.WriteLine("Grp: " + grp.ToString() + " : " + obj.ToString());
}
}
}
}
答案 2 :(得分:0)
using System.DirectoryServices.AccountManagement;
bool IsDomainUser()
{
return UserPrincipal.Current.ContextType == ContextType.Domain;
}