How to check C # if user account is active

How can I check with C # if the local user account is active (namely the local administrator account)?

What I really want is a C # replacement for "Active Account" = "Yes" (or "No") from the "net user Administrator" command.

I'm afraid this question looks like a duplicate of this one, but I don’t know what to pass for the parameter for the root DirectoryEntry object. I tried different things, such as "ldap: //" + Environment.MachineName, "ldap: //127.0.0.1", "WinNT: //" + Environment.MachineName, but none of them worked. I get an exception caused by a call to find.FindAll () in all three cases.

+5
source share
5 answers
class Program
{
    static void Main(string[] args)
    {

        // Create the context for the principal object. 
        PrincipalContext ctx = new PrincipalContext(ContextType.Machine);

        UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "Administrator");
        Console.WriteLine(String.Format("Administrator is enable: {0}", u.Enabled));

    }
}
+5
source

You can request WMI Win32_UserAccount

This is boilerplate code created by MS wmi code creator as a link;

using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Disabled FROM Win32_UserAccount WHERE name = 'alexk'");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_UserAccount instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Disabled: {0}", queryObj["Disabled"]);
                    Console.ReadKey();
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

(I would bundle the tool, but as usual, msdn links are dead)

+1
source

.

 var server = "YOURMACHINENAME";
 var username = "Guest"; 
 var de = new DirectoryEntry {Path = "WinNT://" + server + ",computer"};
 var result = de.Children
     .Cast<DirectoryEntry>()
     .First<DirectoryEntry>(d => d.SchemaClassName == "User" && d.Properties["Name"].Value.ToString() == username);

 var flags = (int)result.Properties["UserFlags"].Value;
 var disabled = (flags & 2) == 2;
+1

, , win32 api funcion NetGetUserInfo, , .

pinvoke.net - , , 2,

0

All Articles