Determining existing local windows accounts via .NET
In a C# application I use the following code to determine existing local windows accounts (inkl. filtering build-in security principals for some reasons):
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)
{
....
}
Now I am looking for an alternative method/way to determine existing local windows accounts like above because this method is not very stable --> sometimes an COMException is thrown ( when executing searcher.Get() ):
System.Runtime.InteropServices.COMException (0x8007开发者_StackOverflow社区06BA) at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
The exception occurs non-determinstic in my opinion.
I do not exactly understand what u need but here is a good example of getting all windows accounts on the system
http://csharptuning.blogspot.com/2007/09/how-to-get-list-of-windows-user-in-c.html
and to get current system user u simply write
System.Security.Principal.WindowsIdentity.GetCurrent()
you can also do something like this
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();
}
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
- Managing Directory Security Principals in the .NET Framework 3.5
- MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a context (including a "machine" context for the local accounts), and then easily find users and/or groups:
// 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
}
The new S.DS.AM makes it really easy to play around with users and groups in AD:
精彩评论