C# 如何获得系统范围的.NET核心运行时环境的基本路径?
当我运行C# 如何获得系统范围的.NET核心运行时环境的基本路径?,c#,msbuild,.net-core,C#,Msbuild,.net Core,当我运行dotnet--info时,我还收到了以下信息: Runtime Environment: ... Base Path: C:\Program Files\dotnet\sdk\1.0.0 在.NETCoreApp框架下运行的C#应用程序中,有没有办法通过编程获得该值?我对它的Sdks子目录特别感兴趣,因为在处理一些.NET核心项目时,我需要将它提供给MSBuild的托管实例。因此,像AppContext.BaseDirectory这样的属性对我没有用处,因为它们指向当前应用程
dotnet--info
时,我还收到了以下信息:
Runtime Environment:
...
Base Path: C:\Program Files\dotnet\sdk\1.0.0
在.NETCoreApp框架下运行的C#应用程序中,有没有办法通过编程获得该值?我对它的Sdks
子目录特别感兴趣,因为在处理一些.NET核心项目时,我需要将它提供给MSBuild的托管实例。因此,像AppContext.BaseDirectory
这样的属性对我没有用处,因为它们指向当前应用程序的路径
我可能会启动dotnet--info
并解析其结果,但我想知道是否存在一种更优雅的方式。谢谢
编辑:最初错误地使用了dotnet--version
而不是dotnet--info
您可以从应用程序运行“dotnet--info”命令并解析输出
又快又脏:
class Program
{
static void Main(string[] args)
{
var basePath = GetDotNetCoreBasePath();
Console.WriteLine();
Console.ReadLine();
}
static String GetDotNetCoreBasePath()
{
Process process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
FileName = "dotnet",
Arguments = "--info"
}
};
process.Start();
process.WaitForExit();
if (process.HasExited)
{
string output = process.StandardOutput.ReadToEnd();
if (String.IsNullOrEmpty(output) == false)
{
var reg = new Regex("Base Path:(.+)");
var matches = reg.Match(output);
if (matches.Groups.Count >= 2)
return matches.Groups[1].Value.Trim();
}
}
throw new Exception("DotNet Core Base Path not found.");
}
}
安装此软件包后
ApplicationEnvironment.ApplicationBasePath
将为您提供所需内容。我通过查看dotnet
源代码发现了这一点
我也这么认为,但不幸的是,它返回了编译后的应用程序程序程序集所在的目录,例如
..\myapp\bin\Debug\netcoreapp1.0
。它只适用于dotnet--info
,因为CLI工具本身位于所需的目录中(例如C:\Program Files\dotnet\sdk\1.0.0
)。