пятница, 3 февраля 2012 г.

Get local system users info using C#


 var path = string.Format("WinNT://{0},computer", Environment.MachineName);

            using (var computerEntry = new DirectoryEntry(path))
            {
                foreach (DirectoryEntry childEntry in computerEntry.Children)
                {
                    if (childEntry.SchemaClassName == "User")
                    {
                        using (var context = new PrincipalContext(ContextType.Machine))
                        {
                            using (var user = UserPrincipal.FindByIdentity(context, childEntry.Name))
                            {
                               //Do something here
                            }
                        }
                    }
                }
            }


Alternative code:


var ps = new PrincipalSearcher { QueryFilter = new UserPrincipal(new PrincipalContext(ContextType.Machine, Environment.MachineName)) { Name = "*" } };

            foreach (var secPrinc in ps.FindAll().OrderBy(u => u.Name))
            {
                var u = secPrinc;

                System.Windows.Application.Current.Dispatcher.Invoke(
                    (Action)
                    (() =>
                     _collection.Add(
                         new UserInfo()
                             {
                                 Name = u.Name,
                                 Description = u.Description,
                                 SID = u.Sid.ToString(),
                                 IsEnabled = (u as UserPrincipal).Enabled.ToString(),
                                 Groups = u.GetGroups().Aggregate(string.Empty, (all, next) => all + (all != string.Empty ? "," : string.Empty) + next.Name),
                                 LastLogon = (u as UserPrincipal).LastLogon,
                                 LastPasswordSet = (u as UserPrincipal).LastPasswordSet,
                             })));
            }

Комментариев нет:

Отправить комментарий