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