在 .NET Framework 中,我会检查类似这样的内容:
(new WindowsPrincipal(WindowsIdentity.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator)
我现在开始使用 .NET Standard 2.0 来定位项目,其中似乎没有
WindowsPrincipal
或 WindowsIdentity
。
检查进程是否使用 Sudo/Administrator 运行的正确方法是什么?
您可以引用从 .NET Standard 2.0 库提供 .NET Standard 资源的其他包。这意味着您应该能够添加对@JeroenMostert提到的包的引用:
System.Security.Principal.Windows
并且您应该能够使用它。
需要注意的是,该代码只能在 Windows 上运行。如果您从 .NET Core 2.0 应用程序使用它并在 Windows 上运行它,则代码应该可以工作。
如果没有,请在此处提交问题:https://github.com/dotnet/corefx/issues/new
我为那些像我一样最近正在寻找答案并最终在这篇文章中找到答案的人提供答案。
当然,这个解决方案可能不是100%合适,但通常,大多数情况下,问题是通过检查用户id是否为0来解决的。
例如,您可以这样检查用户 ID:https://github.com/dotnet/runtime/issues/25118#issuecomment-367407469
检查您是否在 Unix 上以 root 身份运行:
- 将 PackageReference 添加到 Mono.Posix.NETStandard
- 将 IsAdminstrator 更改为以下内容:
public static bool IsAdministrator =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
new WindowsPrincipal(WindowsIdentity.GetCurrent())
.IsInRole(WindowsBuiltInRole.Administrator) :
Mono.Unix.Native.Syscall.geteuid() == 0;