views:

137

answers:

3

I looking the way to run DOS/windows batch directly from C# code without saving it as .BAT file before. I'm mainly interested to run DOS command with combination of stdin stream.

Let's say I need execute something like that:

echo 'abcd' | programXXX.exe -arg1 --getArgsFromStdIn

After that programXXX.exe will take 'abcd' string as -arg1

What I'm doing now is just create bat file in TMP directory and running it, deleting after execution.
What I need is run it "on the fly" just from .NET code without saving to file previously.
(Main reason is security, but also dont want to leave rubbish when program crashh etc)

Do you know how to archive that?

+2  A: 

You can use Process.Start.

It will take several parameters, and you can pass through command line parameters to it.

Oded
Good for commands, not for temporary Batch Files
Henk Holterman
He wants to avoid temporary Batch Files.
Oded
I definitely want to avoid temp files!@Oded - did you mean (in that particular example) I shall use RedirectStandardInput = true when starting process?
Maciej
That should work.
Oded
OK just tested - works well for my example!What about multiline batch ?
Maciej
+1  A: 

I would offer two suggestions

  1. use redirected IO and launch the program from in your code
  2. you can use power shell like in this tutorial
rerun
+1  A: 

A switch to PowerShell (PSH) would give you much greater ability to execute commands. PSH executes in process, and multiple command lines can be executed in a single runspace (scope/context) with full control over input and output object pipelines:

var runspace = RunspaceFactory.CreateRunspace();
PSSnapInException pex;
var loadedSnapIn = Runspace.RunspaceConfiguration.AddPSSnapIn(SnapInName, out pex);
runspace.Open();
var pipe = runspace.CreatePipeline(commandline);
var output = pipe.Invoke();

This creates the runspace, loads a snapin (i.e. extra custom commands), sets up a command and executes it, collecting the collection of returned objects.

Richard