c#:如何知道'用户帐户'是否存在于Windows?

问题描述:

我有两个问题。c#:如何知道'用户帐户'是否存在于Windows?

1)如何知道我的Windows操作系统(vista)上是否存在“用户帐户”?我需要一个独立机器的这个信息。我的意思是,机器不加入任何域。

2)我也想知道用户是否属于一个组?例如。是管理员组的用户'管理员'部分还是不是?

任何人都可以请帮助..

我曾尝试下面的代码,并为我工作很好..

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; 
    } 

你可能想看看这个forum post。它会通过机器上的用户通过WMI为您提供枚举列表。然后你可以检查你的账户是否在那里。该论坛也链接到code project上的一篇文章。我相信你也可以通过WMI获得组员资格,但我可能是错的。

使用以下代码可以计算出本地帐户是否通过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; 
} 

现在越来越组成员身份是有点困难,你可以很容易地使用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; 
} 
+0

非常感谢虫族。它正在工作,但有点慢。无论如何,再次感谢! – satya 2010-01-12 11:02:06

+0

如果您将NTAccount更改为此NTAccount acct = new NTAccount(Environment.MachineName,name);它的速度更快。因人而异。 – Tollo 2012-07-26 11:01:49