views:

1530

answers:

2

Hi, I've been trying to look around the various .NET class library's for some where I can get the logged in user of the local machine, either connected to a domain or not. So far

System.Security.Principal.WindowsPrincipal LoggedUser = System.Threading.Thread.CurrentPrincipal as 
System.Security.Principal.WindowsPrincipal;
// This returns the username
LoggedUser.Identity.Name

This will return the user's name, however is there any way of getting the session details, something that you would see in AD or user logged in, session duration, etc.. the context of the user, actions such as Workstation locked, the presence of the user basiclly.

If you have any idea, it would be much appreciated. Thanks in advance.

+1  A: 

You can get some of that such as start time from WMI look at WMI_LogonSession

JoshBerke
A: 

You can query Active Directory for much of the data that you need through LDAP queries using the System.DirectoryServices namespace. For example, the sample below shows the user's last logon time.

Of course, this only works for domain users.

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace ADMadness
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectorySearcher search = new DirectorySearcher("LDAP://DC=my,DC=domain,DC=com");
            search.Filter = "(SAMAccountName=MyAccount)";
            search.PropertiesToLoad.Add("lastLogonTimeStamp");


            SearchResult searchResult = search.FindOne();


            long lastLogonTimeStamp = long.Parse(searchResult.Properties["lastLogonTimeStamp"][0].ToString());
            DateTime lastLogon = DateTime.FromFileTime(lastLogonTimeStamp);


            Console.WriteLine("The user last logged on at {0}.", lastLogon);
            Console.ReadLine();
        }
    }
}
Aaron Daniels