Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running commands in cmd using C#

I want to run a cmd and run some command in it. I wrote this code:

Process p = new Process();
ProcessStartInfo info =new ProcessStartInfo();

info.FileName = "cmd.exe";
info.WorkingDirectory = this.workingDirectory;
info.RedirectStandardInput = true;
info.UseShellExecute = false; 
info.CreateNoWindow = true;
p.StartInfo = info;

var x=p.Start();
using (StreamWriter sw = p.StandardInput)
{
    if (sw.BaseStream.CanWrite)
    {
        sw.WriteLine(@"set path=c:\temp"+ ";%path%");
        sw.WriteLine(@"@MyLongproces.exe");
    }
}

But it doesn't work:

  1. I can not see command window (even when I set info.CreateNoWindow to false).
  2. My command is not running.

What is the problem? and how can I fix it?

  • Update1

This code doesn't work:

  string binDirectory = Path.Combine(FileSystem.ApplicationDirectory, this.binFolderName);
  ProcessStartInfo info = new ProcessStartInfo("cmd", @"/c " + Path.Combine(binDirectory, command));
  info.RedirectStandardInput = false;
  info.RedirectStandardOutput = true;
  info.UseShellExecute = false;
  info.CreateNoWindow = false;
  System.Diagnostics.Process proc = new System.Diagnostics.Process();
  proc.StartInfo = info;
  proc.Start();
  string result = proc.StandardOutput.ReadToEnd();

No cmd window is shown and result it "".

But this code works:

     Process.Start(Path.Combine(binDirectory, command));

The problem with above code is:

  1. I can not define the working directory.
  2. It shows a CMD window when I don't want it to show.

Any idea why it is not working?

like image 469
mans Avatar asked Apr 16 '13 12:04

mans


1 Answers

You are setting the CreateNoWindow option:

info.CreateNoWindow = true;

ProcessStartInfo.CreateNoWindow - true if the process should be started without creating a new window to contain it; otherwise, false. The default is false.

like image 60
CloudyMarble Avatar answered Oct 29 '22 05:10

CloudyMarble