在运行时获取 --launch-profile 值 .net core

Gab*_*oso 5 c# xunit .net-core

我正在运行 xUnit 测试,并且设置了不同的配置文件(不同的开发人员、阶段、产品)。我能够获取 launchSettings.json 并加载配置文件设置。但因为我无法在运行时获取当前配置文件,所以我无法区分它们。

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

Mon*_*rso 0

操作系统

使用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];
Run Code Online (Sandbox Code Playgroud)

视窗

为了使它在 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();
Run Code Online (Sandbox Code Playgroud)

获取进程的命令行参数:

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(" ");
Run Code Online (Sandbox Code Playgroud)