0

if i open the cmd and type whoami/logonid i get back a Logon id number ,

after some research i found this line :

var logonId = UserPrincipal.Current.Sid;

this code gets me a number that starts like the whoami/lgonid but they different.

i dont wish to run the whoami throw c# code i just need to get the result number.

for example : if i write whoami/user i got the user name, the equivalent in c# code is WindowsIdentity.GetCurrent().Name;

i need the same for logonid

  • If you use `whoami /user` you get the same SID as from the API. I wonder what the difference is from `/user` and `/logonid` – Hans Kilian Jul 04 '18 at 07:00
  • me to, /user giving me the same as the code i wrote in the question /logonid giving me different number –  Jul 04 '18 at 07:13
  • Seems like `/logonid` gives you a session id that changes whenever you log out and back in. You can get the logon id using the GetTokenInformation function in advapi32.dll, but that's unmanaged code so more difficult to call than managed code. – Hans Kilian Jul 04 '18 at 07:42

2 Answers2

0

Use ProcessStartInfo.RedirectStandardOutput when you instantiate whoami. You can parse the text you get for the logonid.

PepitoSh
  • 1,774
  • 14
  • 13
0

You can use ProcessStartInfo.RedirectStandardInput and ProcessStartInfo.RedirectStandardoutput Property to achieve this.

Following is sample code:

public static string GetLoginId()
{
    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "cmd.exe";
    p.Start();

    StreamWriter myStreamWriter = p.StandardInput;
    myStreamWriter.WriteLine("whoami /logonid");

    // To avoid deadlocks, always read the output stream first and then wait.
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    Console.WriteLine(output);
}
cse
  • 4,066
  • 2
  • 20
  • 37
  • this code do not work for me. –  Jul 04 '18 at 07:05
  • and i dont wont to run the whoami.exe i just wont the retrun number –  Jul 04 '18 at 07:08
  • for example if i write whoami in cmd i get the computer username the equivalent in c# code is : WindowsIdentity.GetCurrent().Name –  Jul 04 '18 at 07:10
  • +1 for the efforts. @B.katan: You should have indicateed in the OP that you do not want to execute whoami. From your wording I -and apparently others as well- gathered that you are looking for a solution to invoke whoami and parse the result. – PepitoSh Jul 04 '18 at 07:14
  • you right , i edited the question –  Jul 04 '18 at 08:10