Is there a way to execute the following command through C#?
.\binary.exe < input > output
I am trying to use System.Diagnostics.Process but I was wondering if there is a direct exec style command in C#. Any suggestions?
Not directly, but you can redirect output from a console stream (as you may have figured out, considering you're trying to use the Process class), as noted here on MSDN: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
There is also an example here on SO: Redirect console output to textbox in separate program
Wrap that into your own class and it will basically become an "exec" style command.
Basically you need to redirect the standard input and output to your program and write them to the files you want
ProcessStartInfo info = new ProcessStartInfo("binary.exe");
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
Process p = Process.Start(info);
string Input;
// Read input file into Input here
StreamWriter w = new StreamWriter(p.StandardInput);
w.Write(Input);
w.Dispose();
StreamReader r = new StreamReader(p.StandardOutput);
string Output = r.ReadToEnd();
r.Dispose();
// Write Output to the output file
p.WaitForExit();
Related
I have a batch file setEnv.bat.
#echo off
set input=C:\Program Files\Java\jdk1.8.0_131
SET MY_VAR=%input%
I want to run this batch file from C# application and want to access the newly set value of MY_VAR from c# application.
C#:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName= "D:\\Check\\SetJavaHome.bat";
proc.StartInfo.WorkingDirectory =
System.Environment.CurrentDirectory;
proc.Start();
string myVar = Environment.GetEnvironmentVariable("MY_VAR");
Can someone help me in getting this working as expected?
Thanks in advance.
Check out this answer with the sample code:
https://stackoverflow.com/a/51189308/9630273
Getting the Environment variables directly from another process is not possible, but a simple workaround can be like:
Create a dummy bat file (env.bat) that will execute the required bat and echo the environment variable.
Get the output of this env.bat inside the process execution of C#.
The reason why you want to do this is a bit vague but if your only option is to run that batchfile from a call to Process.Start then the following trickery will let you promote the environment vars from the batch file to your own process.
This is the batch file I use:
set test1=fu
set test2=bar
The followng code opens a standard Command Prompt and then uses the StandardInput to send commands to the command prompt and receive the results with OutputDataReceived event. I basically caputure the output of the SET command and the parse over its result. For each line that contains an environment var and value I call Environment.SetEnvironmentVaruable to set the environment in our own process.
var sb = new StringBuilder();
bool capture = false;
var proc = new Process();
// we run cms on our own
proc.StartInfo.FileName = "cmd";
// we want to capture and control output and input
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
// get all output from the commandline
proc.OutputDataReceived += (s, e) => { if (capture) sb.AppendLine(e.Data); };
// start
proc.Start();
proc.BeginOutputReadLine(); // will start raising the OutputDataReceived
proc.StandardInput.WriteLine(#"cd \tmp"); // where is the cmd file
System.Threading.Thread.Sleep(1000); // give it a second
proc.StandardInput.WriteLine(#"setenv.cmd"); // run the cmd file
System.Threading.Thread.Sleep(1000); // give it a second
capture = true; // what comes next is of our interest
proc.StandardInput.WriteLine(#"set"); // this will list all environmentvars for that process
System.Threading.Thread.Sleep(1000); // give it a second
proc.StandardInput.WriteLine(#"exit"); // done
proc.WaitForExit();
// parse our result, line by line
var sr = new StringReader(sb.ToString());
string line = sr.ReadLine();
while (line != null)
{
var firstEquals = line.IndexOf('=');
if (firstEquals > -1)
{
// until the first = will be the name
var envname = line.Substring(0, firstEquals);
// rest is the value
var envvalue = line.Substring(firstEquals+1);
// capture what is of interest
if (envname.StartsWith("test"))
{
Environment.SetEnvironmentVariable(envname, envvalue);
}
}
line = sr.ReadLine();
}
Console.WriteLine(Environment.GetEnvironmentVariable("test2")); // will print > bar
This will bring the environment variables that are set by a command file into your process.
Do note you can achieve the same by creating a command file that first calls your batchfile and then start your program:
rem set all environment vars
setenv.cmd
rem call our actual program
rem the environment vars are inherited from this process
ConsoleApplication.exe
The latter is easier and works out of the box, no brittle parsing code needed.
I am starting a process using Process.Start(ProcessStartInfo). It currently brings up a console window and the output of the process is displayed there until the process completes, in which case the console window closes automatically.
The process outputs a lot of text, so I do not just want to redirect this output to a string, like examples I have found so far.
How can I get the text of the console output to go into a text log file?
ProcessStartInfo myPSI = new ProcessStartInfo();
myPSI.FileName = myFileName;
myPSI.Arguments = myArgs;
myPSI.CreateNoWindow = false;
myPSI.UseShellExecute = false;
myPSI.WindowStyle = ProcessWindowStyle.Hidden;
try
{
using (Process exeProcess = Process.Start(myPSI))
{
exeProcess.WaitForExit();
}
}
catch
{
}
You need to use output redirection. See here: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
You can redirect the output to whatever you want... for example a stream... you can even process the output in a separate thread if you want to - for source code and details see http://www.codeproject.com/KB/threads/ReadProcessStdoutStderr.aspx
I am new to C# so please sorry if i make no sense in my question. In my application which is C# DLL need to open command prompt, give a plink command for Linux system to get a system related string and set that string as environment variable. I am able to do this when i create C# console application, using plink command to get the string on command prompt and use to set it environment variable using process class in C# to open plink as separate console process. But, in C# DLL i have to open cmd.exe 1st and then give this command which i don't know how can i achieve? I tried through opening cmd.exe as process and then trying to redirect input and output to process and give command and get string reply, but no luck. Please let me know any other way to solve this.
Thanks for answers,
Ashutosh
Thanks for your quick replys. It was my mistake in writing code sequence. Now few changes and the code is working like charm. Here is code,
string strOutput;
//Starting Information for process like its path, use system shell i.e. control process by system etc.
ProcessStartInfo psi = new ProcessStartInfo(#"C:\WINDOWS\system32\cmd.exe");
// its states that system shell will not be used to control the process instead program will handle the process
psi.UseShellExecute = false;
psi.ErrorDialog = false;
// Do not show command prompt window separately
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
//redirect all standard inout to program
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
//create the process with above infor and start it
Process plinkProcess = new Process();
plinkProcess.StartInfo = psi;
plinkProcess.Start();
//link the streams to standard inout of process
StreamWriter inputWriter = plinkProcess.StandardInput;
StreamReader outputReader = plinkProcess.StandardOutput;
StreamReader errorReader = plinkProcess.StandardError;
//send command to cmd prompt and wait for command to execute with thread sleep
inputWriter.WriteLine("C:\\PLINK -ssh root#susehost -pw opensuselinux echo $SHELL\r\n");
Thread.Sleep(2000);
// flush the input stream before sending exit command to end process for any unwanted characters
inputWriter.Flush();
inputWriter.WriteLine("exit\r\n");
// read till end the stream into string
strOutput = outputReader.ReadToEnd();
//remove the part of string which is not needed
int val = strOutput.IndexOf("-type\r\n");
strOutput = strOutput.Substring(val + 7);
val = strOutput.IndexOf("\r\n");
strOutput = strOutput.Substring(0, val);
MessageBox.Show(strOutput);
I explained the code so far..., thanks a lot
How can I set up two external executables to run from a c# application where stdout from the first is routed to stdin from the second?
I know how to run external programs by using the Process object, but I don't see a way of doing something like "myprogram1 -some -options | myprogram2 -some -options". I'll also need to catch the stdout of the second program (myprogram2 in the example).
In PHP I would just do this:
$descriptorspec = array(
1 => array("pipe", "w"), // stdout
);
$this->command_process_resource = proc_open("myprogram1 -some -options | myprogram2 -some -options", $descriptorspec, $pipes);
And $pipes[1] would be the stdout from the last program in the chain. Is there a way to accomplish this in c#?
Here's a basic example of wiring the standard output of one process to the standard input of another.
Process out = new Process("program1.exe", "-some -options");
Process in = new Process("program2.exe", "-some -options");
out.UseShellExecute = false;
out.RedirectStandardOutput = true;
in.RedirectStandardInput = true;
using(StreamReader sr = new StreamReader(out.StandardOutput))
using(StreamWriter sw = new StreamWriter(in.StandardInput))
{
string line;
while((line = sr.ReadLine()) != null)
{
sw.WriteLine(line);
}
}
You could use the System.Diagnostics.Process class to create the 2 external processes and stick the in and outs together via the StandardInput and StandardOutput properties.
Use System.Diagnostics.Process to start each process, and in the second process set the RedirectStandardOutput to true, and the in the first RedirectStandardInput true. Finally set the StandardInput of the first to the StandardOutput of the second . You'll need to use a ProcessStartInfo to start each process.
Here is an example of one of the redirections.
I have to use an other application (console) to pass some parameter to this program and inside my C# program get the output of that program. I would like not to see the console (all invisible to the user). How can I do that?
Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("YOUPROGRAM_CONSOLE.exe" );
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
Console.WriteLine(myString);
myProcess.Close();
Source : MSDN
Edited:
If you require to get the Error Message you will need to use Async operation. You can use asynchronous read operations to avoid these dependencies and their deadlock potential. Alternately, you can avoid the deadlock condition by creating two threads and reading the output of each stream on a separate thread.