Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute dotnet command with Process in C#

Tags:

c#

I have following C# lines of code where open process and run dotnet command to open my console application (created with .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();

The command Arguments result is:

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 ""

But for ev.Data from OutputDataReceived event looks like:

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

and that's all...

I expected to run dotnet command to dll.

If I run manually the result command dotnet .... above, works fine. But not from my C# code. Why ?

like image 625
Snake Eyes Avatar asked Jul 22 '26 09:07

Snake Eyes


1 Answers

Because cmd returns:

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

You need to call

procStartInfo.FileName = "dotnet"
like image 106
Access Denied Avatar answered Jul 24 '26 23:07

Access Denied



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!