Hi.
This is my answer to yours question:
"Can u kindly explain how may I get the user name??" For reaching necessary result you need to use WinApi and P/Invoke.
General workflow will be the next:
1) Call WTSGetActiveConsoleSessionId() to get the active console session id (VERY important, as the interactive session is NOT always session 1, even on client systems). This API will also return a -1 if there is no active user logged into the interactive session (that is, logged in locally to the physical machine, as opposed to using RDP).
2) Pass the session id from the previous API call to WTSQueryUserToken() to get an open token that reprents the user logged into the console.
3) Call DuplicateTokenEx() to convert the impersonation token (from WTSQueryUserToken) into a primary token.
4) Call CreateEnvironmentBlock() to create a new environment for the process (optional, but if you don't, the process won't have one).
5)Impersonate user using primary user token from step #3 and impersonate user:
WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate.DangerousGetHandle());
impersonationContext = tempWindowsIdentity.Impersonate();
5) Invoke Method GetProcessInfoByPID(....) *see in the of solution*
6)If you created an environment block, then you need to call DestroyEnvironmentBlock, otherwise you will generate a memory leak. The process is given a separate copy of the environment block when it launches, so you are only destroying local data.
public static string GetProcessInfoByPID(int PID, out string User, out string Domain)
{
User = String.Empty;
Domain = String.Empty;
OwnerSID = String.Empty;
string processname = String.Empty;
try
{
ObjectQuery sq = new ObjectQuery
("Select * from Win32_Process Where ProcessID = '" + PID + "'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq);
if (searcher.Get().Count == 0)
return OwnerSID;
foreach (ManagementObject oReturn in searcher.Get())
{
string[] o = new String[2];
oReturn.InvokeMethod("GetOwner", (object[])o);
processname = (string)oReturn["Name"];
User = o[0];
if (User == null)
User = String.Empty;
Domain = o[1];
if (Domain == null)
Domain = String.Empty;
string[] sid = new String[1];
oReturn.InvokeMethod("GetOwnerSid", (object[])sid);
OwnerSID = sid[0];
return OwnerSID;
}
}
catch
{
return OwnerSID;
}
return OwnerSID;
}