C #: detection if running as superuser, both on Windows and Mono

this question is actually a duplicate of this . I want to determine if my program runs either with privilege escalation in Winows through UAC, or as root in Unix / Mono.

How can I do this in C #?

+3
source share
1 answer

Something like the function below will take care of the end of the Unix / Mono question. By the way, I didn’t actually collect or run this, but you get the point.

private bool AmIRoot()
{
   //Declarations:
   string fileName = "blah.txt",
          content = "";

   //Execute shell command:
   System.Diagnostics.Process proc = new System.Diagnostics.Process();
   proc.EnableRaisingEvents=false; 
   proc.StartInfo.FileName = "whoami > " + fileName;
   proc.StartInfo.Arguments = "";
   proc.Start();
   proc.WaitForExit();

   //View results of command execution:
   StreamReader sr = new StreamReader(fileName);
   content = sr.ReadLine();
   sr.Close();

   //Clean up magic file:
   File.Delete(fileName);

   //Return to caller:
   if(content == "root")
      return true;
   else
      return false;
}
+2
source

Source: https://habr.com/ru/post/1772871/


All Articles