通过.NET确定现有的本地Windows帐户

时间:2011-07-06 11:47:53

标签: c# .net windows interop com-interop

在C#应用程序中,我使用以下代码来确定现有的本地Windows帐户(由于某些原因,过滤内置安全主体):

ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Account Where LocalAccount = True AND Status = 'OK' AND (SidType = 1 OR SidType = 5)" + 
                 " AND (SID <> 'S-1-3-3' AND SID <> 'S-1-3-2' AND SID <> 'S-1-5-9' " + 
                 "      AND SID <> 'S-1-5-8' AND SID <> 'S-1-5-10' AND SID <> 'S-1-5-12' " + 
                 "      AND SID <> 'S-1-2-0')");
ManagementObjectCollection objects = searcher.Get();
foreach (ManagementBaseObject obj in objects)
{
    ....
}

现在我正在寻找替代方法/方式来确定上面的现有本地Windows帐户,因为这种方法不是很稳定 - &gt;有时会抛出 COMException (执行searcher.Get()时):

  

System.Runtime.InteropServices.COMException   (0x800706BA)at   System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(的Int32   errorCode,IntPtr errorInfo)at   System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()

在我看来,异常是非确定性的。

2 个答案:

答案 0 :(得分:2)

我并不完全明白你需要什么,但这是一个在系统上获取所有Windows帐户的好例子

http://csharptuning.blogspot.com/2007/09/how-to-get-list-of-windows-user-in-c.html

要获得当前的系统用户,只需编写

即可
System.Security.Principal.WindowsIdentity.GetCurrent()

你也可以做这样的事情

static void Main(string[] args)
    {
        SelectQuery query = new SelectQuery("Win32_UserAccount");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
        foreach (ManagementObject envVar in searcher.Get())
        {
            Console.WriteLine("Username : {0}", envVar["Name"]);
        }

        Console.ReadLine();

    }

答案 1 :(得分:2)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义上下文(包括本地帐户的“计算机”上下文),然后轻松查找用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);

// find all users - define a "UserPrincipal" as your "QBE" principal
UserPrincipal qbeUser = new UserPrincipal(ctx);

// enumerate all users
PrincipalSearcher searcher = new PrincipalSearcher(qbeUser);

foreach(Principal p in searcher.FindAll())
{
    // do something here
}

新的S.DS.AM使得在AD中使用用户和群组变得非常容易: