How to interact with cmd.exe using C#? - c#

I want to call cmd.exe using C#.
And I want to write multiple cmd commands in C#.
the most important keys is that:
I want to interact with cmd window.the next command is typed according to the last command output.
But now I have tried ,it can input multiple commands but only one output or one outputErr.
I want to achieve one command one output,and the next command is also the same cmd window rather than a new cmd window?
How to solve this problem.
the example code is like this
string[] message = new string[2];
ProcessStartInfo info = new ProcessStartInfo();
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.UseShellExecute = false;
info.FileName = "cmd.exe";
info.CreateNoWindow = true;
Process proc = new Process();
proc.StartInfo = info;
proc.Start();
using (StreamWriter writer = proc.StandardInput)
{
if (writer.BaseStream.CanWrite)
{
foreach (string q in command)
{
writer.WriteLine(q);
}
writer.WriteLine("exit");
}
}
message[0] = proc.StandardError.ReadToEnd();
if (output)
{
message[1] = proc.StandardOutput.ReadToEnd();
}
return message;

The problem is that cmd is a cli application, so proc.StandardOutput.ReadToEnd() will block your thread, you can't simply put the ReadToEnd() in your loop (to execute multiple command).
In my demo, I start a new thread to handle the output.so that i won't block my command input.
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
CreateNoWindow = true
}
};
proc.Start();
StringBuilder sb = new StringBuilder();
var outStream = proc.StandardOutput;
var inStream = proc.StandardInput;
inStream.WriteLine("mkdir test");
Task.Run(() =>
{
while (true)
{
Console.WriteLine(outStream.ReadLine());
}
});
Console.WriteLine("dir");
inStream.WriteLine("dir");
Console.WriteLine("mkdir test");
inStream.WriteLine("mkdir test");
Console.WriteLine("dir");
inStream.WriteLine("dir");
Console.ReadLine();
}
forgive my poor english,

Related

How to run hidden R task?

I'm calling Rscript.exe from c# windows forms app, and the cmd window opens up for a few milliseconds. The python solution was easy: simply started pythonw.exe instead of python.exe
Here is the function:
private void runr()
{
orig = richTextBox1.Text;
System.IO.File.WriteAllText(#"C:\cp.R", richTextBox1.Text);
string cmd = #"C:\cp.R";
string args = #"";
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Program Files\R\R-3.2.3\bin\Rscript.exe";
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
StreamReader reader2 = process.StandardError;
string err = reader2.ReadToEnd();
richTextBox1.Text = result;
if (!string.IsNullOrEmpty(err))
richTextBox1.Text += "\nError:\n" + err;
}
}
}
Setting start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; does not work.
Set the ProcessStartInfo.CreateNoWindow Property to true. This prevents the system from creating a console window for the new process.

how to execute a command prompt command in my own console application

how can i make my console application window to behave like a command prompt window and execute my command line arguments?
This should get you started:
public class Program
{
public static void Main(string[] args)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
proc.Start();
new Thread(() => ReadOutputThread(proc.StandardOutput)).Start();
new Thread(() => ReadOutputThread(proc.StandardError)).Start();
while (true)
{
Console.Write(">> ");
var line = Console.ReadLine();
proc.StandardInput.WriteLine(line);
}
}
private static void ReadOutputThread(StreamReader streamReader)
{
while (true)
{
var line = streamReader.ReadLine();
Console.WriteLine(line);
}
}
}
The basics are:
open cmd.exe process and capture all three streams (in, out, err)
pass input from outside in
read output and transfer to your own output.
The "Redirect" options are important - otherwise you can't use the process' respective streams.
The code above is very basic, but you can improve on it.
I believe you are looking for this
var command = "dir";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);

How to make sure a batch file is executed properly through a CMD from a c# applicaiton?

I have a c# applications which writes to a batch file and executes it. The application to be started and the path of application will be written in batch file and executed. which is working fine.
How can i make sure that the application launched successfully via my batch file run in command prompt ?
Is there any value that cmd returns after executing a batch file ? or any other ideas please...
Code i am using now :
public void Execute()
{
string LatestFileName = GetLastWrittenBatchFile();
if (System.IO.File.Exists(BatchPath + LatestFileName))
{
System.Diagnostics.ProcessStartInfo procinfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
procinfo.UseShellExecute = false;
procinfo.RedirectStandardError = true;
procinfo.RedirectStandardInput = true;
procinfo.RedirectStandardOutput = true;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(procinfo);
System.IO.StreamReader stream = System.IO.File.OpenText(BatchPath + LatestFileName);
System.IO.StreamReader sroutput = process.StandardOutput;
System.IO.StreamWriter srinput = process.StandardInput;
while (stream.Peek() != -1)
{
srinput.WriteLine(stream.ReadLine());
}
stream.Close();
process.Close();
srinput.Close();
sroutput.Close();
}
else
{
ExceptionHandler.writeToLogFile("File not found");
}
}
I'm not familiar with batch files, but if there is possibility to return exit code from it, you can check it with System.Diagnostics.Process.ExitCode
Process process = Process.Start(new ProcessStartInfo{
FileName = "cmd.exe",
Arguments = "/C myfile.bat",
UseShellExecute = false,
});
process.WaitForExit();
Console.WriteLine("returned {0}", process.ExitCode);
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filename);
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit(2000);
if (listFiles.HasExited)
{
string output = myOutput.ReadToEnd();
MessageBox.Show(output);
}

How do I hide a console application user interface when using Process.Start?

I want to run a console application that will output a file.
I user the following code:
Process barProcess = Process.Start("bar.exe", #"C:\foo.txt");
When this runs the console window appears. I want to hide the console window so it is not seen by the user.
Is this possible? Is using Process.Start the best way to start another console application?
Process p = new Process();
StreamReader sr;
StreamReader se;
StreamWriter sw;
ProcessStartInfo psi = new ProcessStartInfo(#"bar.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.CreateNoWindow = true;
p.StartInfo = psi;
p.Start();
This will start a child process without displaying the console window, and will allow the capturing of the StandardOutput, etc.
Check into ProcessStartInfo and set the WindowStyle = ProcessWindowStyle.Hidden and the CreateNoWindow = true.
If you would like to retrieve the output of the process while it is executing, you can do the following (example uses the 'ping' command):
var info = new ProcessStartInfo("ping", "stackoverflow.com") {
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
var cmd = new Process() { StartInfo = info };
cmd.Start();
var so = cmd.StandardOutput;
while(!so.EndOfStream) {
var c = ((char)so.Read()); // or so.ReadLine(), etc
Console.Write(c); // or whatever you want
}
...
cmd.Dispose(); // Don't forget, or else wrap in a using statement
We have done this in the past by executing our processes using the Command Line programatically.

Execute multiple command lines with the same process using .NET

I'm trying to execute multiple commands without create a new process each time. Basically, I want to start the DOS command shell, switch to the MySQL command shell, and execute a command. Here's how I am calling the procedure (also below). Also, how do I handle the "\"'s in the command?
ExecuteCommand("mysql --user=root --password=sa casemanager", 100, false);
ExecuteCommand(#"\. " + Environment.CurrentDirectory + #"\MySQL\CaseManager.sql", 100, true);
private void ExecuteCommand(string Command, int Timeout, Boolean closeProcess)
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
ProcessInfo.CreateNoWindow = false;
ProcessInfo.UseShellExecute = false;
Process = Process.Start(ProcessInfo);
Process.WaitForExit(Timeout);
if (closeProcess == true) { Process.Close(); }
}
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}
const string strCmdText = "/C command1&command2";
Process.Start("CMD.exe", strCmdText);
Couldn't you just write all the commands into a .cmd file in the temp folder and then execute that file?
As another answer alludes to under newer versions of Windows it seems to be necessary to read the standard output and/or standard error streams otherwise it will stall between commands. A neater way to do that instead of using delays is to use an async callback to consume output from the stream:
static void RunCommands(List<string> cmds, string workingDirectory = "")
{
var process = new Process();
var psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = workingDirectory;
process.StartInfo = psi;
process.Start();
process.OutputDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
process.ErrorDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
using (StreamWriter sw = process.StandardInput)
{
foreach (var cmd in cmds)
{
sw.WriteLine (cmd);
}
}
process.WaitForExit();
}
I prefer to do it by using a BAT file.
With BAT file you have more control and can do whatever you want.
string batFileName = path + #"\" + Guid.NewGuid() + ".bat";
using (StreamWriter batFile = new StreamWriter(batFileName))
{
batFile.WriteLine($"YOUR COMMAND");
batFile.WriteLine($"YOUR COMMAND");
batFile.WriteLine($"YOUR COMMAND");
}
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c " + batFileName);
processStartInfo.UseShellExecute = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
Process p = new Process();
p.StartInfo = processStartInfo;
p.Start();
p.WaitForExit();
File.Delete(batFileName);
ProcessStartInfo pStartInfo = new ProcessStartInfo();
pStartInfo.FileName = "CMD";
pStartInfo.Arguments = #"/C mysql --user=root --password=sa casemanager && \. " + Environment.CurrentDirectory + #"\MySQL\CaseManager.sql"
pStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pStartInfo);
The && is the way to tell the command shell that there is another command to execute.
A command-line process such cmd.exe or mysql.exe will usually read (and execute) whatever you (the user) type in (at the keyboard).
To mimic that, I think you want to use the RedirectStandardInput property: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx
You could also tell MySQL to execute the commands in the given file, like so:
mysql --user=root --password=sa casemanager < CaseManager.sql
You need to READ ALL data from input, before send another command!
And you can't ask to READ if no data is avaliable... little bit suck isn't?
My solutions... when ask to read... ask to read a big buffer... like 1 MEGA...
And you will need wait a min 100 milliseconds... sample code...
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("cmd.exe", "")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oStartInfo.RedirectStandardInput = True
oStartInfo.CreateNoWindow = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim Response As String = String.Empty
Dim BuffSize As Integer = 1024 * 1024
Dim x As Char() = New Char(BuffSize - 1) {}
Dim bytesRead As Integer = 0
oProcess.StandardInput.WriteLine("dir")
Threading.Thread.Sleep(100)
bytesRead = oProcess.StandardOutput.Read(x, 0, BuffSize)
Response = String.Concat(Response, String.Join("", x).Substring(0, bytesRead))
MsgBox(Response)
Response = String.Empty
oProcess.StandardInput.WriteLine("dir c:\")
Threading.Thread.Sleep(100)
bytesRead = 0
bytesRead = oProcess.StandardOutput.Read(x, 0, BuffSize)
Response = String.Concat(Response, String.Join("", x).Substring(0, bytesRead))
MsgBox(Response)
End Sub
End Class
I'm using these methods:
public static Process StartCommand(params string[] commands) => StartCommand(commands, false);
public static Process StartCommand(IEnumerable<string> commands, bool inBackground, bool runAsAdministrator = true)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
if(commands.Any()) p.StartInfo.Arguments = #"/C " + string.Join("&&", commands);
if (runAsAdministrator)
p.StartInfo.Verb = "runas";
if (inBackground)
{
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
p.Start();
return p;
}
Enjoy...

Categories