Redirect process input and use shell execute - c#

Is it possible to redirect just stdin but also allow stdout to be written to the console?
I have a process which starts child processes and needs to read the output of those processes, but also display it in the console. Is it possible? I tried to just create my own console process but I can't write to it unless I UseShellExecute and the purpose is to show the output in the console.
protected void startp() {
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.Arguments = "/k";
//Can't redirect output without UseShellExecute = false
psi.RedirectStandardInput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = false;
p.StartInfo = psi;
p.Start();
//Can't write to StandardInput with UseShellExecute = true
p.StandardInput.WriteLine("#ECHO OFF");
p.StandardInput.WriteLine("echo | set /p=Child Process");
Console.ReadLine();
p.StandardInput.WriteLine("exit");
}

Related

Run windows command without cmd.exe from C#

I am attempting to run a windows command (e.g. whoami) without calling cmd.exe (or powershell) directly using C#.
Within VB this is possible using CreateObject(WScript.Shell) it obviously does not have to be the same method as within the VB, although that would be nice, but I just do not want to call cmd.exe directly.
How would I be able to achieve this?
This runs a console program, waits for exit and reads the output. I changed the cmd to ping since that takes longer and I can verify no console window opens.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "ping.exe";
startInfo.Arguments = "google.com";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
// This wasn't needed
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
textBox1.Text = processTemp.StandardOutput.ReadToEnd();
processTemp.WaitForExit();
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
You could call whoami.exe and capture the output directly.
The key is UseShellExecute = false to run the executable directly.
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #$"{Environment.ExpandEnvironmentVariables("%systemroot%")}\system32\whoami.exe",
Arguments = // Put any command line arguments here
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
string line = proc.StandardOutput.ReadToEnd();

Problem with running batch files from within my application

I've been trying to create a simple application to backup my Windows Server databases aswell as a whole server backup.
For this I want to use batch files which are being executed by my application.
I tried several approaches but for some reason it always fails so I'd be happy if you could help me out.
Batch file BACKUPSERVER:
wbadmin start backup -backupTarget:D: -include:C: -allCritical -quiet
I have to run the bat as administrator or it fails due to missing permissions.
C# code:
static Task<int> RunProcessAsync(string fileName)
{
............
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Verb = "runas";
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C \"D:\\SQLBACKUP\\BACKUPSERVER.bat\"";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
Debugging says 'wbadmin wasnt found'. 'runas' activated or not doesn't make any difference.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fileName;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = false;
// startInfo.Verb = "runas";
var process = new Process
{
StartInfo = { FileName = fileName },
EnableRaisingEvents = true
};
process.StartInfo = startInfo;
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
Also doesn't work.
Any ideas?
EDIT:
I'm able to run commands like shutdown but wbadmin doesn't work whatsoever...
This is how I solved the problem:
Make sure ure compiling for 64bit if u intend to use your application on 64bit system, otherwise it will redirect to different subfolders and wont find 'wbadmin.exe'.
Run wbadmin with ProcessStart or run a batch but without direct cmd input, so use this with filename = batch file or wbadmin with startInfo.Arguments:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fileName;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = false;
// startInfo.Verb = "runas";
var process = new Process
{
StartInfo = { FileName = fileName },
EnableRaisingEvents = true
};
process.StartInfo = startInfo;
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
Make sure u request administrator rights

Open bat file by c#, but it's closed immediately [duplicate]

I currently have a portion of code that creates a new Process and executes it from the shell.
Process p = new Process();
...
p.Start();
p.WaitForExit();
This keeps the window open while the process is running, which is great. However, I also want to keep the window open after it finishes to view potential messages. Is there a way to do this?
It is easier to just capture the output from both the StandardOutput and the StandardError, store each output in a StringBuilder and use that result when the process is finished.
var sb = new StringBuilder();
Process p = new Process();
// redirect the output
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
// hookup the eventhandlers to capture the data that is received
p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);
// direct start
p.StartInfo.UseShellExecute=false;
p.Start();
// start our event pumps
p.BeginOutputReadLine();
p.BeginErrorReadLine();
// until we are done
p.WaitForExit();
// do whatever you need with the content of sb.ToString();
You can add extra formatting in the sb.AppendLine statement to distinguish between standard and error output, like so: sb.AppendLine("ERR: {0}", args.Data);
This will open the shell, start your executable and keep the shell window open when the process ends
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
p.StartInfo = psi;
p.Start();
p.WaitForExit();
or simply
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
Process p = Process.Start(psi);
if(p != null && !p.HasExited)
p.WaitForExit();
Be carefull espacially on switch /k, because in many examples is usually used /c.
CMD /K Run Command and then return to the CMD prompt.
CMD /C Run Command and then terminate
var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/k yourmainprocess.exe";
p.Start();
p.WaitForExit();
Regarding: "Member Process.Start(ProcessStartInfo) cannot be accessed with an instance reference; qualify it with a type name instead"
This fixed the problem for me....
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
Process p = Process.Start(psi);
p.WaitForExit();

How will I show command prompt text in a richtextBox?

I have this code which I want the value to show in a richtextbox.
Process proc = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.FileName = "netsh.exe";
psi.Arguments = "wlan show profile";
proc.StartInfo = psi;
proc.Start();
Set your UseShellExecute to false and RedirectStandardOutput to true and you can use StandardOutput property of the proc and then you can iterate end of the stream.
From documentation;
To use StandardOutput, you must set ProcessStartInfo.UseShellExecute
to false, and you must set ProcessStartInfo.RedirectStandardOutput to
true. Otherwise, reading from the StandardOutput stream throws an
exception.
Then you can assign which line do you want with ReadLine to your RichTextBox.
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
then
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// Assign this line to your RichTextBox.
}

Run EXE from Windows From pass in static inputs

currently I have a process that runs, but it requires the user to enter
y <return>
<return>
The code I am using is as follows
ProcessStartInfo psi = new ProcessStartInfo();
string exepath = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();
Process proc = new Process();
psi.FileName = exepath + #"\lib\dnaml";
psi.RedirectStandardInput = true;
psi.Arguments = "y\r \r";
psi.UserShellExecute = true;
proc.StartInfo = psi;
proc.Start();
proc.WaitForExit();
I want to hard type these inputs in. Any suggestions? Thanks
The Arguments property corresponds to the command-line, not data entered via standard input.
The RedirectStandardInput property is part of the puzzle. Then you also need to write to the stream connected to the StandardInput property. Also note that standard input redirection is incompatible with ShellExecute, it needs CreateProcess to work. So set UseShellExecute = false.
psi.RedirectStandardInput = true;
psi.UseShellExecute = false;
proc.StartInfo = psi;
proc.Start();
proc.StandardInput.WriteLine("y ");
proc.StandardInput.WriteLine();
proc.WaitForExit();

Categories

Resources