4

I am trying to check if .Net code is running as sudo/admin on Linux. It works on Windows but throws exception on Linux.

How do I check if app is run by admin/sudo on Ubuntu Linux by using .NET Core2.0 build-in class?

Here is the code I have tried:

using System;
using System.Security.Principal;

namespace smallTestsCore
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Program.IsAdministrator);
            Console.ReadLine();
        }
        public static bool IsAdministrator =>
            new WindowsPrincipal(WindowsIdentity.GetCurrent())
                .IsInRole(WindowsBuiltInRole.Administrator);
    }
}

The code works on Windows, but does not work on Linux:

Exception has occurred: CLR/System.PlatformNotSupportedException
An unhandled exception of type 'System.PlatformNotSupportedException' occurred in
System.Security.Principal.Windows.dll: 'Windows Principal functionality is not supported on this platform.'
  at System.Security.Principal.WindowsIdentity.GetCurrent()
   at adminTst.Program.get_IsAdministrator() in /home/user/adminTst/Program.cs:line 15
   at adminTst.Program.Main(String[] args) in /home/user/adminTst/Program.cs:line 11
jww
  • 97,681
  • 90
  • 411
  • 885
Reven
  • 776
  • 2
  • 8
  • 23

0 Answers0