在C#中使用Process执行dotnet命令

时间:2018-09-24 07:14:54

标签: c#

我有以下C#代码行,在其中打开进程并运行dotnet命令以打开我的控制台应用程序(使用.net standard / core创建)

var args = new Dictionary<string, string> {
 { "-p", "title"},
 { "-l", "games"},
 ...
};

var arguments = string.Join(" ", args.Select((k) => string.Format("{0} {1}", k.Key, "\"" + k.Value + "\"")));

var dllPath = @"C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll";
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.FileName = "C:\....\cmd.exe";
procStartInfo.Arguments = $"dotnet \"{dllPath}\" {arguments}";
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;

StringBuilder sb = new StringBuilder();
Process pr = new Process();
pr.StartInfo = procStartInfo;

pr.OutputDataReceived += (s, ev) =>
{
    if (string.IsNullOrWhiteSpace(ev.Data))
    {
        return;
    }

    string[] split = ev.Data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
    int.TryParse(split[split.Length - 1], out output);
};

pr.ErrorDataReceived += (s, err) =>
{
    // do stuff here
};

pr.EnableRaisingEvents = true;
pr.Start();
pr.BeginOutputReadLine();
pr.BeginErrorReadLine();

pr.WaitForExit();

命令Arguments的结果是:

dotnet "C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll" -p "title" -l "games" -s "" -r "none" -k "0" -d "/path/" -f ""

但是对于ev.Data中的OutputDataReceived,事件看起来像:

Microsoft Windows [Version 10.0.16299.665]
(c) 2017 Microsoft Corporation. All rights reserved.

仅此而已...

我期望对dll运行dotnet命令。

如果我手动运行上面的结果命令dotnet ....,则工作正常。但不是来自我的C#代码。为什么?

1 个答案:

答案 0 :(得分:3)

因为cmd返回:

Microsoft Windows [Version 10.0.16299.665] 
(c) 2017 Microsoft Corporation. All rights reserved.

您需要致电

procStartInfo.FileName = "dotnet"