我正在尝试检查.Net代码是否在Linux上以sudo / admin身份运行。它适用于Windows但在Linux上引发异常。
如何使用.NET Core2.0内置类检查app是否由Ubuntu Linux上的admin / sudo运行?
以下是我尝试的代码:
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);
}
}
该代码适用于Windows,但不适用于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