Bob*_*bbo 39 c# windows visual-studio-2008 winforms
有谁知道如何确定你的c#代码运行的平台,例如它是在linux或windows上运行,以便我可以在运行时执行不同的代码.
我有一个ac#windows应用程序,我想构建目标Windows和Linux平台.
到目前为止,我创建了两个指向同一组源代码文件的项目文件.然后,我使用条件编译语句之一称为LINUX的项目.
在实际代码中存在差异的情况下,我使用条件编译语句使用编码语句,例如
#if (LINUX)
' do something
#endif
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?我真的不想拥有2个项目文件.
提前致谢.
Mar*_*erl 74
您可以使用System.Environment.OSVersion.Platform
以下方法检测执行平台:
public static bool IsLinux
{
get
{
int p = (int) Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
Run Code Online (Sandbox Code Playgroud)
如何检测执行平台?
可以使用该
System.Environment.OSVersion.Platform
值来检测执行平台.然而,在每种情况下,正确检测Unix平台都需要更多的工作.框架的第一个版本(1.0和1.1)没有包含PlatformID
Unix的任何值,因此Mono使用值128.较新的框架2.0将Unix添加到PlatformID枚举,但遗憾的是,具有不同的值:4和更新的版本.NET在Unix和MacOS X之间区分,为MacOS X引入了另一个值6.这意味着为了正确检测在Unix平台上运行的代码,您必须检查三个值(4,6和128).这确保了在Mono CLR 1.x运行时以及Mono和Microsoft CLR 2.x运行时执行时,检测代码将按预期工作.
Jon*_*mit 36
.NET 5+ 具有该类OperatingSystem
,因此现在您可以:
if (OperatingSystem.IsWindows())
DoSomething();
Run Code Online (Sandbox Code Playgroud)
Ale*_*éau 32
我在微软的一个博客上发现了这个建议:
我们建议您使用RuntimeInformation.IsOSPlatform()进行平台检查.
参考:https: //blogs.msdn.microsoft.com/dotnet/2017/11/16/announcing-the-windows-compatibility-pack-for-net-core/
IsOSPlatform()
取的类型的一个参数OSPlatform
,其具有3个值默认为:Windows
,Linux
和OSX
.它可以用如下:
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
该API是.NET Standard 2.0的一部分,因此可在.NET Core 2.0和.NET Framework 4.7.1中使用.
没有任何这样的方法,但您可以使用此方法有条件地检查它:
public static OSPlatform GetOperatingSystem()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return OSPlatform.OSX;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return OSPlatform.Linux;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return OSPlatform.Windows;
}
throw new Exception("Cannot determine operating system!");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35166 次 |
最近记录: |