[英]Detecting .net core 2.0
在dotnet core 2.0控制台应用程序中,输出:
Console.WriteLine("Hello World from "+ System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
是一个意想不到的价值:
Hello World from .NET Core 4.6.00001.0
有没有办法以编程方式检测.net core 2.0或更高版本,而不是2.0之前的.net核心平台? 我意识到在大多数情况下你可能不应该这样做。 但是在你确实需要这样做的奇怪情况下,你会怎么做?
您可以使用为您预定义的预处理程序符号。 例如:
var isNetCore2 = false;
#if NETCOREAPP2_0
isNetCore2 = true;
#endif
Console.WriteLine($"Is this .Net Core 2: {isNetCore2}");
您可以尝试下面的代码来获取当前的.NET版本。
在.NET Core 1.1和2.0上测试过
public static string GetNetCoreVersion()
{
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
我没有找到任何优雅的方法,但如果你真的需要知道你正在运行哪个版本,你可以像这样执行dotnet --version
:
var psi = new ProcessStartInfo("dotnet", "--version")
{
RedirectStandardOutput = true
};
var process = Process.Start(psi);
process.WaitForExit();
Console.Write(process.StandardOutput.ReadToEnd()); // writes 2.0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.