0 0 0 0


I have a windows service which run a WPF application all the time for all the logged in users which works fine, now in the WPF application i can not get a current username as Environment.UserName; returns 'SYSTEM' which is understandable. so what i thought was to find session id of current process which could be retrieved by Process.GetCurrentProcess().SessionId and then get the list of all users logged in to the machine and looping through it to find the session id match with process session id and later his username.

but i don't how to get the list of all logged in users or i would appreciate if someone can help me with alternative.

Best Answer:

I solve it by executing powershell command "quser" in my WPF application which returns all the logged in users then I am iterating to find session id in which the application is running with user session id and then retrieving his name. below is the function which fetch the username by passing his session id

 private string GetUserName(int SessionId)
                Runspace runspace = RunspaceFactory.CreateRunspace();
                Pipeline pipeline = runspace.CreatePipeline();
                Collection<PSObject> results = pipeline.Invoke();
                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                foreach (string User in stringBuilder.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Skip(1))
                    string[] UserAttributes = User.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries);
                    if (int.Parse(UserAttributes[2].Trim()) == SessionId)
                        return UserAttributes[0].Replace(">", string.Empty).Trim();
                return stringBuilder.ToString();
            catch (Exception ex)
            return string.Empty;

the function can be called by

string CurrentUser = GetUserName(Process.GetCurrentProcess().SessionId);

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs