Reputation: 8044
I execute a command from my C# App.
It runs fine but sometimes I get errors.
My problem is that I cannot see which is the error or any other text in the command window.
It is just blank.
Is there any way I can make the text show up in the execution time same as it is appeared here?
Here is my code:
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
//processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.WorkingDirectory = workingFolder;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("output>>" + e.Data);//MessageBox.Show(e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("error>>" + e.Data);//MessageBox.Show(e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine("ExitCode: {0}", process.ExitCode);
process.Close();
Upvotes: 1
Views: 357
Reputation: 1985
There is nothing wrong with your code, the problem is that you run your program in the wrong path.
Follow these steps to find the path of your app:
Then, in the cmd.exe
go to the path with bunch of cd
commands.
Here is the code:
var command = "echo hello world"; // < ------ example
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
//processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
The output:
output>>hello world output>> error>> ExitCode: 0 Press any key to continue . . .
Also, you can run your app with Ctrl + F5
I know these are so obvious but it's worth to mention them.
You should specify a command, maybe you don't set any command or your command has ~no output~
I change the code, when the user send args
to myapp.exe
, it directs it to run.
static void Main(string[] args)
{
var command = string.Join("", args);
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
...
Output:
C:\Users\Mahan\Source\Repos\ConsoleApp11\ConsoleApp11\bin\Debug>
myapp.exe echo hello
output>>hello world output>> error>> ExitCode: 0
Upvotes: 1
Reputation: 885
I am not an expert on that but I think you can write this code in a try-catch
block and make the exception message be shown on screen using Console.WriteLine()
command.
Upvotes: 1
Reputation: 872
In your first screenshot there is Select
in the title bar of the cmd
window.
Are you aware of the fact that the program gets paused then?
The Select
happens if you click in the window and can be continued by pressing Enter
(if I remember correctly).
If you use Console.WriteLine()
and the cmd
window is not paused, you should see what ever you have written.
Upvotes: 1