0

I'm having some difficulty doing this without using a batch file. What I want to do is when a button is clicked, run the command line with a simple argument that I specify.

Here's my code so far:

ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.UseShellExecute = true;        
startInfo.Arguments = "dir";
Process.Start(startInfo);
string output = Process.StandardOutput.ReadToEnd();
txtblkOutput.Text = output;

However, this just opens a cmd window and nothing happens. The text box remains blank.

However I can do this:

var process = new Process();
process.StartInfo.FileName = "C:/Users/user/Documents/SUB-20 Tool/commands.bat";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
txtblkOutput.Text = output;

Inside the batch file it just says dir. And this works, I get the output sent to my textbox.

Why does this work only with a batch file? Can I do this without it, with just using the argument property?

1 Answer 1

1

This is the excepted behaviour. When you execute cmd.exe with the argument dir, it does not execute the command.

As an exemple, see the screenshot below : enter image description here

The correct way to execute a command in the arguments is the following :

cmd.exe /C <command>
Sign up to request clarification or add additional context in comments.

3 Comments

This would be FileName contents, correct? (process.StartInfo.FileName = "cmd.exe /C dir";) If i do that, i get an error that the system cannot find the file specified.
I split up the command into Filename and Arguments. I used "cmd.exe" for Filename property, and "/C dir" for Arguments property. This worked!
@hereiam That is what I was thinking about. I should have been more explicit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.