如何检查在运行时如操作系统版本Windows或Linux,而不使用条件编译语句 [英] How to check the OS version at runtime e.g. windows or linux without using a conditional compilation statement

查看:589
本文介绍了如何检查在运行时如操作系统版本Windows或Linux,而不使用条件编译语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何确定你的C#代码在运行例如什么平台无论是在Linux或Windows上运行,这样我可以在运行时执行不同的代码。



我有我想建立以适用于Windows和Linux平台的C#Windows应用程序



到目前为止,我已经创造了2指向同一套源代码文件的项目文件。然后我使用条件编译语句称为Linux的项目之一。



如果有实际的代码区别我用使用条件编译语句,如:

 #如果(LINUX)
'做些什么
#ENDIF

是否有这样做的更好的办法?我真的不希望有2个项目文件。



先谢谢了。


解决方案<



<$ p $:/ DIV>

您可以使用 System.Environment.OSVersion.Platform 检测执行平台p> 公共静态布尔IsLinux
{
得到
{
INT p =(INT)Environment.OSVersion.Platform;
回报(P == 4)|| (P = = 6)|| (P == 128);
}
}



Mono FAQ 的:




如何检测执行平台?



执行平台可以通过使用 System.Environment.OSVersion.Platform 值。然而正确地检测Unix平台上,在每一个案件,需要多一点的工作。框架(1.0和1.1)的第一个版本不包括对UNIX的 PlatformID 价值,所以单使用的值128的新框架2.0增加的Unix到PlatformID枚举,但遗憾的是,具有不同的值:4及更高版本的.NET的Unix和MacOS X的区分,为MacOS X的推出又值6



这手段,为了正确地检测在Unix平台上运行,你必须检查三个值(4,6和128)的代码。这确保当在Mono CLR 1.x的运行,并与单声道和微软CLR 2.x的运行时执行如预期检测代码将工作。



Does anyone know how to determine what platform your c# code is running on e.g. whether it is running on linux or windows so that I can execute different code at runtime.

I have a c# windows app that I want to build to target windows and linux platforms.

So far I have created 2 project files pointing to the same set of source code files. I then use a conditional compilation statement one of the projects called LINUX.

Where there are difference in the actual code I use coditional statements using the conditional compilation statement, e.g

#if (LINUX)
 ' do something
#endif

Is there a better way of doing this? I don't really want to have 2 project files.

Thanks in advance.

解决方案

You can detect the execution platform using System.Environment.OSVersion.Platform:

public static bool IsLinux
{
    get
    {
        int p = (int) Environment.OSVersion.Platform;
        return (p == 4) || (p == 6) || (p == 128);
    }
}

From the Mono FAQ:

How to detect the execution platform ?

The execution platform can be detected by using the System.Environment.OSVersion.Platform value. However correctly detecting Unix platforms, in every cases, requires a little more work. The first versions of the framework (1.0 and 1.1) didn't include any PlatformID value for Unix, so Mono used the value 128. The newer framework 2.0 added Unix to the PlatformID enum but, sadly, with a different value: 4 and newer versions of .NET distinguished between Unix and MacOS X, introducing yet another value 6 for MacOS X.

This means that in order to detect properly code running on Unix platforms you must check the three values (4, 6 and 128). This ensure that the detection code will work as expected when executed on Mono CLR 1.x runtime and with both Mono and Microsoft CLR 2.x runtimes.

这篇关于如何检查在运行时如操作系统版本Windows或Linux,而不使用条件编译语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆