Retrieve List of users logged in network using Management Namespace in ASP.Net

mahesh213
 
on Aug 10, 2021 06:00 AM
Sample_135902.zip
491 Views

Hi,

I need to get below details by using management namespace

1) Need to check whethere user is logged in system or not

2) Need to know wthere user is active in system or not

Display system battery status using Management namespace in ASP.Net using C# and VB.Net

can you please help me

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 12, 2021 11:53 PM

Hi mahesh213,

Refer below code.

Added references of System.DirectoryServices and System.Management.

Namespaces

using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Management;

Code

protected void Page_Load(object sender, EventArgs e)
{
    string corporate = "domain name";
    DirectoryEntry entry = new DirectoryEntry("LDAP://" + corporate);
    DirectoryContext objContext = new DirectoryContext(DirectoryContextType.Domain, corporate);
    Domain objDomain = Domain.GetDomain(objContext);
    string ldapPath = objDomain.Name;

    DirectorySearcher dSearch = new DirectorySearcher();
    dSearch.Filter = "(&(objectClass=computer)(objectCategory=computer))";
    dSearch.PropertiesToLoad.Add("cn");
    List<string> allComputers = new List<string>();
    foreach (SearchResult result in dSearch.FindAll())
    {
        string fqn = GetProperty(result, "cn") + "." + ldapPath;
        allComputers.Add(fqn);
    }

    foreach (object o in allComputers)
    {
        ConnectionOptions options = new ConnectionOptions();
        options.EnablePrivileges = true;
        options.Username = "username";
        options.Password = "pass@123";
        options.Impersonation = ImpersonationLevel.Impersonate;
        string fullComputerName = "\\\\" + o.ToString() + "\\root\\cimv2";
        ManagementScope scope = new ManagementScope(fullComputerName, options);
        try
        {
            scope.Connect();
        }
        catch (Exception ex)
        {
            string message = ex.Message;
            continue;
        }
        ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
        ManagementObjectCollection queryCollection = searcher.Get();
        foreach (ManagementObject m in queryCollection)
        {
            Response.Write(string.Format("Logged On User : {0}", m["UserName"]));
        }
    }
}

private static string GetProperty(SearchResult sr, string propertyName)
{
    if (sr.Properties.Contains(propertyName))
    {
        return sr.Properties[propertyName][0].ToString();
    }

    return string.Empty;
}

Reference:

https://social.msdn.microsoft.com/Forums/en-US/5e6ef3c3-ee9c-4d45-9f14-8722b084b710/how-to-check-if-a-user-is-logged-on?forum=csharplanguage