Input & Output from cmd.exe shell - c#

I am trying to create a Windows Forms C# project that interacts with the command prompt shell (cmd.exe).
I want to open a command prompt, send a command (like ipconfig) and then read the results back into the windows form into a string, textbox, or whatever.
Here is what I have so far, but I am stuck. I cannot write or read to the command prompt.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/k dir *.*";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
StreamWriter inputWriter = p.StandardInput;
StreamReader outputWriter = p.StandardOutput;
StreamReader errorReader = p.StandardError;
p.WaitForExit();
}
}
}
Any help would be greatly appreciated.
Thanks.

Here is a SO question that will give you the information you need:
How To: Execute command line in C#, get STD OUT results
Basically, you ReadToEnd on your System.IO.StreamReader.
So, for example, in your code you would modify the line StreamReader errorReader = p.StandardError; to read
using(StreamReader errorReader = p.StandardError)
{
error = myError.ReadToEnd();
}

var yourcommand = "<put your command here>";
var procStart = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + yourcommand);
procStart.CreateNoWindow = true;
procStart.RedirectStandardOutput = true;
procStart.UseShellExecute = false;
var proc = new System.Diagnostics.Process();
proc.StartInfo = procStart;
proc.Start();
var result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);

Related

Process.StartInfo.FileName coming up blank

So, I am creating a C# program to run a command prompt command when a button is pressed, this is the code that executes when the button is pressed:
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
string arg = textBox1.Text + "& exit";
process.StartInfo.Arguments = arg;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo = startInfo;
process.Start();
string outp = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
StreamWriter myStreamWriter = process.StandardInput;
myStreamWriter.WriteLine(textBox1.Text);
textBox2.Text = outp;
process.WaitForExit();
}
Maybe it's something obvious that I am missing, if it is, I am sorry(I am kind of a beginner at C#), but I can't, for the life of me, figure out why I get an exception thrown out of system.dll that reads as follows:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll
Additional information: Cannot start process because a file name has not been provided.
However, I have provided a file name (line 5 of code snippet). Any help is GREATLY appreciated, thanks.
P.S.
This code uses:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
To run properly.
process.StartInfo = startInfo; //Here problem is there, you are
//refreshing "process.StartInfo" with "startInfo". As "startInfo" is empty in your code.
//So use below code
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
string arg = textBox1.Text + "& exit";
startInfo.Arguments = arg;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = "cmd.exe";
process.StartInfo = startInfo;
process.Start();

How to auto fill cmd prompt

I Have a C# program; when I hit a button I want it to open a CMD window, then automatically type in the cmd window and run that said command. So far I have this from 4 hours of research. But nothing is working.
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
//p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ipconfig");
Any idea on how to fill in a certain text then automatically run it when the button is hit?
With StandardInput and StandardOutput redirected, you cannot see the new window opened. If you want to create a new cmd window and run ipconfig in it, you could do this:
var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c ipconfig & pause";
p.Start();
I agree that if all you want to do is execute "ipconfig" you could just invoke it instead of cmd.exe. Assuming you want to do other things with cmd.exe, here is an example of how to invoke it, have it execute a command, and then terminate (using the /K switch instead of /C will keep cmd.exe running):
using System;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C ipconfig";
p.Start();
var output = p.StandardOutput.ReadToEnd();
Console.Write(output);
Console.ReadKey();
}
}
}

Save The Cmd output into txt file in C#

How Can i save the CMD Commands into txt file in C#
or how can i display command prompt in C#
here is my code
private void button1_Click(object sender, EventArgs e)
{
var p = new Process();
string path = #"C:\Users\Microsoft";
string argu = "-na>somefile.bat";
ProcessStartInfo process = new ProcessStartInfo("netstat", argu);
process.RedirectStandardOutput = false;
process.UseShellExecute = false;
process.CreateNoWindow = false;
Process.Start(process);
p.StartInfo.WorkingDirectory = path;
p.StartInfo.FileName = "sr.txt";
p.Start();
p.WaitForExit();
}
You can redirect the standard output:
using System;
using System.Diagnostics;
using System.IO;
class Program
{
static void Main()
{
//
// Setup the process with the ProcessStartInfo class.
//
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\7za.exe"; // Specify exe name.
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
//
// Start the process.
//
using (Process process = Process.Start(start))
{
//
// Read in all the text from the process with the StreamReader.
//
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
}
Code is from here
Also look to this answer: redirecting output to the text file c#

Set Path for URL Protocol in c#

So I created an URL protocol to run an application with the command arguments.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
namespace iw4Protocol
{
class Program
{
static void Main(string[] args)
{
RegistryKey key = Registry.ClassesRoot.OpenSubKey("gameProtocol");
if (key == null)
{
string iw4FullPath = Directory.GetCurrentDirectory();
gameProtocol protocol = new gameProtocol();
protocol.RegisterProtocol(gameFullPath);
}
else
{
RegistryKey gamepathkey = Registry.ClassesRoot.OpenSubKey("gameProtocol");
string gamepath = gamepathkey.GetValue("gamepath").ToString();
Environment.SetEnvironmentVariable("path",gamepath);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"test.exe";
startInfo.Arguments = Environment.CommandLine;
Process.Start(startInfo);
}
}
}
}
The problem is that the program need some files to get launched but it can't load them because the path isn't 'set'.
How I can set this path to launch all these needed files (like /cd command)?
If you want to set the PATH environment variable and use it in your process, add it to the Environment variables but you have to set UseShellExecute to false in that case:
ProcessStartInfo startInfo = new ProcessStartInfo();
// set environment
startInfo.UseShellExecute = false;
startInfo.EnvironmentVariables["PATH"] += ";" + gamepath;
// you might need more Environment vars, you're on your own here...
// start the exe
startInfo.FileName = #"test.exe";
startInfo.Arguments = Environment.CommandLine;
// added for debugging
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
var p = new Process();
p.StartInfo = startInfo;
using(var sw = new StreamWriter(File.Create("c:\\temp\\debug.txt"))) // make sure C:\temp exist
{
p.OutputDataReceived += (sender, pargs) => sw.WriteLine(pargs.Data);
p.ErrorDataReceived += (sender, pargs) => sw.WriteLine(pargs.Data);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
}

Reading output from console through asp.net

I am using this code to pass two numbers as input to an .exe of a C program file through asp.net and after that trying to read the output from console. I am having problem to read any output from the console.
My asp.net code is.
string returnvalue;
Process p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.FileName = ("C:\\Users\\...\\noname01.exe");
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();
Thread.Sleep(500);
SendKeys.SendWait("1");
Thread.Sleep(500);
SendKeys.SendWait("~");
Thread.Sleep(500);
SendKeys.SendWait("2");
Thread.Sleep(500);
SendKeys.SendWait("~");
Thread.Sleep(500);
StreamReader sr = p.StandardOutput;
returnvalue = sr.ReadToEnd();
System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Hussain\\Documents\\Visual Studio 2012\\WebSites\\WebSite4\\Data\\StudentOutput.txt");
file.WriteLine(returnvalue);
My C code to which am passing inputs is.
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
Any kind of help required.
I'm not sure if SendKeys works in this case as the console window is hidden and SendKeys is supposed to write to the active window and the child process windw is hidden, but if you use StandardInput.WriteLine to send data to the child process it should work.
This code works and creates a file AdderOutput.txt with the following content:
Enter two numbers to add
Sum of entered numbers = 3
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string returnvalue;
Process p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.FileName = ("D:\\adder.exe");
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();
Thread.Sleep(500);
p.StandardInput.WriteLine("1");
Thread.Sleep(500);
p.StandardInput.WriteLine("2");
Thread.Sleep(500);
StreamReader sr = p.StandardOutput;
returnvalue = sr.ReadToEnd();
System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\AdderOutput.txt");
file.WriteLine(returnvalue);
file.Flush();
file.Close();
}
}
}
It might not be the best solution - it's been a while since I did C# - but it seems to work. The adder.exeused is the C program from your code.

Categories