sat*_*tya 12 c# windows user-accounts
我如何知道我的Windows操作系统(Vista)上是否存在用户帐户?我需要来自未加入任何域的独立计算机的此信息.
我想知道用户是否属于某个群组,例如是否是"管理员"群组的用户"管理员"部分?
tyr*_*nid 11
如果System.Security.Principal使用以下代码通过命名空间存在本地帐户,则可以计算出来.
bool AccountExists(string name)
{
bool bRet = false;
try
{
NTAccount acct = new NTAccount(name);
SecurityIdentifier id = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
bRet = id.IsAccountSid();
}
catch (IdentityNotMappedException)
{
/* Invalid user account */
}
return bRet;
}
Run Code Online (Sandbox Code Playgroud)
现在获得组成员资格稍微困难一些,您可以使用该WindowsPrinciple.IsInRole方法轻松地为当前用户执行此操作(从WindowsIdentify.GetCurrent()方法创建原则).
正如所指出的那样,我认为没有办法在不诉诸PInvoke或WMI的情况下获得任何其他东西.所以这里有一些代码来检查WMI的组成员身份.
bool IsUserInGroup(string name, string group)
{
bool bRet = false;
ObjectQuery query = new ObjectQuery(String.Format("SELECT * FROM Win32_UserAccount WHERE Name='{0}' AND LocalAccount=True", name));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection objs = searcher.Get();
foreach (ManagementObject o in objs)
{
ManagementObjectCollection coll = o.GetRelated("Win32_Group");
foreach (ManagementObject g in coll)
{
bool local = (bool)g["LocalAccount"];
string groupName = (string)g["Name"];
if (local && groupName.Equals(group, StringComparison.InvariantCultureIgnoreCase))
{
bRet = true;
break;
}
}
}
return bRet;
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过以下代码并且对我来说工作正常..
public bool IsUserMemberOfGroup(string userName, string groupName)
{
bool ret = false;
try
{
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry userGroup = localMachine.Children.Find(groupName, "group");
object members = userGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
DirectoryEntry member = new DirectoryEntry(groupMember);
if (member.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase))
{
ret = true;
break;
}
}
}
catch (Exception ex)
{
ret = false;
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)