Command prompt not opening but executing the command in .Net

Viewed 252

I am new to .net, I have a task in which I need to open command prompt from a particular directory and then execute few commands in it. All this needs to be done by code. I tried the similar for testing purpose in below code

            var res = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            Process cmd = new Process();
            cmd.StartInfo.WorkingDirectory = @"E:\";
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.Start();

            cmd.StandardInput.WriteLine("mkdir test");
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.StandardOutput.ReadToEnd();
            cmd.WaitForExit();

The problem is, it is making directory as the command says but command prompt is not opening. For the actual task the command is different in which I am starting the server. So for that the command prompt needs to open and show the details of server.

1 Answers

The issue is this line:

cmd.StartInfo.CreateNoWindow = true;

I feel like the name of that property is pretty self explanitory, but here is what the MSDN entry about it says:

Property Value Boolean true if the process should be started without creating a new window to contain it; otherwise, false. The default is false.

Also, the line regarding shell execute is also likely to prevent a window from appearing:

cmd.StartInfo.UseShellExecute = false;

I suggest you look into all the properties of StartInfo that you're using here because this looks like you copy pasted code without understanding it at all.

Related