3

I try to run a process.start() for command in command line, and try to get the output into string or some usefull locaiton. The output will consist of several rows ( like DIR command ). I read how to do it but it doesn' t work for me. It runs but then got into loop and does not stop.See below. any ideas?

        ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("cmd.exe", 
                                                                  @" /k dir");
        Process myProcess = new Process();
        myProcess.StartInfo.RedirectStandardOutput = true;
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.FileName = "cmd.exe";
        myProcess.StartInfo.Arguments = @" /k dir";
        myProcess.Start();         

        string ppp = myProcess.StandardOutput.ReadToEnd();
        myProcess.WaitForExit();
Shai
  • 25,159
  • 9
  • 44
  • 67
MottiNissim
  • 31
  • 1
  • 4
  • possible duplicate of [Running Command line from an ASPX page, and returning output to page](http://stackoverflow.com/questions/247668/running-command-line-from-an-aspx-page-and-returning-output-to-page) – Shai Mar 01 '12 at 14:24
  • possible duplicate of [Redirect Standard Output Efficiently in .NET](http://stackoverflow.com/questions/164736/redirect-standard-output-efficiently-in-net) – M.Babcock Mar 01 '12 at 14:35
  • well, thanks for the fast reply. it did not work for me...still stuck and doing nothing, is if in a loop – MottiNissim Mar 01 '12 at 14:39
  • You might be interested in [this post](http://www.codeducky.org/process-handling-net), which covers many of the intricacies of working with .NET processes, particularly around working with input and output. It recommends the [MedallionShell](https://github.com/madelson/MedallionShell) library, which simplifies handling process io streams – ChaseMedallion Aug 29 '14 at 11:20

1 Answers1

3

Your process will never exit on its own because you're passing the /K flag to cmd.exe which will keep the window open (and hence the process alive) after it runs your command.

/K Carries out the command specified by string but remains

I think what you're looking for here is to use /C which will close the command window after it runs your command.

/C Carries out the command specified by string and then terminates

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
  • That is true, it helped and worked. What if you had a command that does not terminate itself in the cmd.exe , like running the process: cmd.exe sqlplus bla bla bla ? The sqlplus itself will not terminate so the whole process will still get stuck... – MottiNissim Mar 02 '12 at 09:32