Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running cmd commands via .NET?

Tags:

c#

.net

process

cmd

System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;

And now for some background...

string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

omgwut is something like this:

copy /b a.wav + b.wav + ... + y.wav + z.wav output.wav

And nothing happens at all. So obviously something's wrong. I also tried "copy" as the executable, but that doesn't work.

like image 275
unrelativity Avatar asked Nov 28 '22 20:11

unrelativity


2 Answers

Try the prefixing your arguments to cmd with /C, effectively saying cmd /C copy /b t.wav ...

According to cmd.exe /? using

/C <command>

Carries out the command specified by string and then terminates

For your code, it might look something like

// .. 
proc0.StartInfo.Arguments = "/C " + omgwut;

Notes:

  • A good way to test whether your command is going to work is to actually try it from a command prompt. If you try to do cmd.exe copy ... you'll see that the copy doesn't occur.
  • There are limits to the length of the arguments you can pass as arguments. From MSDN: "The maximum string length is 2,003 characters in .NET Framework applications and 488 characters in .NET Compact Framework applications."
  • You can bypass the shelling out to command by using the System.IO classes to open the files and manually concatenate them.
like image 154
Daniel LeCheminant Avatar answered Dec 09 '22 14:12

Daniel LeCheminant


Try this it might help you.. Its working with my code.

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
  }
  catch (Exception objException)
  {
  // Log the exception
  }
like image 45
vikas latyan Avatar answered Dec 09 '22 15:12

vikas latyan