我找不到一个真正有效的方法来正确检测我的C#程序运行在哪个平台上(Windows / Linux / Mac),特别是在Mac上返回Unix,很难与Linux平台区分!
因此,我做了一些不那么理论化、更实用的东西,基于Mac的特殊性。
我将工作代码发布为答案。如果它对您也管用/可以改进,请评论。
谢谢!
回复:
这是可行的代码!
public enum Platform
{
Windows,
Linux,
Mac
}
public static Platform RunningPlatform()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Unix:
// Well, there are chances MacOSX is reported as Unix instead of MacOSX.
// Instead of platform check, we'll do a feature checks (Mac specific root folders)
if (Directory.Exists("/Applications")
& Directory.Exists("/System")
& Directory.Exists("/Users")
& Directory.Exists("/Volumes"))
return Platform.Mac;
else
return Platform.Linux;
case PlatformID.MacOSX:
return Platform.Mac;
default:
return Platform.Windows;
}
}
uname
命令。如果上面的代码返回Platform.Unix
,那么可以启动一个子进程运行uname -o
,过滤结果是否包含linux
或darwin
,然后相应地返回相应的枚举值。 - Gabi Barrientos