获取--在运行时启动配置文件值.net核心



我正在运行xUnit测试,并设置了不同的配置文件(不同的dev、stage、prod(。我可以获得launchSettings.json并加载配置文件设置。但由于我无法在运行时获取当前配置文件,因此无法区分它们。

有没有一种方法可以让我在运行时获得传递给参数dotnet run --launch-profile <MY_PROFILE_NAME>的概要文件值?

linux

使用ps命令,我们可以获得给定pid的进程的命令。因此,我们必须获取进程的pid并提取其命令行参数。

// when you execute 'dotnet run' command, actuall program is being executed
// as a child proess of the 'dotnet' command, so we'll have to extract parent
// 'pid' of process which is being reported by 'Environment.ProcessId'
// 'ps --pid 123 -f --format ppid --no-headers' will report parent process id 
// of process with pid 123
var getParentIdProcess = Process
.Start(new ProcessStartInfo("ps", $"--pid {Environment.ProcessId} -f --format ppid --no-headers") 
{ RedirectStandardError = true, RedirectStandardOutput = true, });
getParentIdProcess.WaitForExit();
var parentProcessId = getParentIdProcess.StandardOutput.ReadToEnd()
.TrimEnd()
.TrimStart();
// when we know parent 'pid' we can extract command line of it via the same
// 'ps' command. 
// 'ps --pid 123 --format args --no-headers' will return 'dotnet run --launch-profile ...'
var getCommandOfAProcess = Process
.Start(new ProcessStartInfo("ps", $"--pid {parentProcessId} --format args --no-headers")
{ RedirectStandardError = true, RedirectStandardOutput = true, });
getCommandOfAProcess.WaitForExit();
var arguments = getCommandOfAProcess.StandardOutput.ReadToEnd()
.Split(" ");
// extract value of --launch-profile flag
var launchProfileValue = arguments[Array.IndexOf(arguments, "--launch-profile") + 1];

windows

要使其在windows上工作,您必须进行一些调整,因为那里没有ps命令,所以我们将使用wmic指令。但总体思路是一样的。

正在获取父进程id:

var getParentIdProcess = Process
.Start(new ProcessStartInfo("cmd", $" /c wmic process where (processid={Environment.ProcessId}) get parentprocessid")
{ RedirectStandardError = true, RedirectStandardOutput = true, });
getParentIdProcess.WaitForExit();
var parentProcessId = getParentIdProcess.StandardOutput.ReadToEnd()
.TrimEnd()
.TrimStart()
.Split("n")
.Last();

获取进程的命令行参数:

var getCommandOfAProcess = Process
.Start(new ProcessStartInfo("cmd", $"/c wmic path win32_process where "processid like {parentProcessId}"  get commandline")
{ RedirectStandardError = true, RedirectStandardOutput = true, });
getCommandOfAProcess.WaitForExit();
var arguments = getCommandOfAProcess.StandardOutput.ReadToEnd()
.TrimEnd()
.TrimStart()
.Split("n")
.Last()
.Split(" ");

最新更新