C# process RedirectStandardOutput not redirecting - c#

I want to redirect standardoutput of a Process in a richTextBox. Here is my process configuration,
string command = "/K perl C:\\Server.pl ";
ProcessStartInfo startInfo = new ProcessStartInfo();
Process proc = new Process();
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
proc.StartInfo = startInfo;
proc.OutputDataReceived += (s, ea) => this.richTextBox1.AppendText(ea.Data);
proc.Start();
proc.BeginOutputReadLine();
Here is my Server.pl file
print "Server1 \n";
while(1)
{
print "Server \n";
sleep 1;
}
But when I run the program the cmd.exe is just black and nothing printed in richTextBox. but when I change the
startInfo.RedirectStandardOutput = false;
I have this out put in my cmd.exe:
Server1
Server
Server
Server
...
How I can work around this issue ?

Might be as simple as disabling output buffering in your perl script. This is done using the $| special variable (see perlvar).
$| = 1;
print "Server1 \n";
...

Related

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

"StandardOut has not been redirected or the process hasn't started yet" when reading console command output in C#

Thanks to #user2526830 for the code. Based on that code I added few lines to my program since I want to read the output of the SSH command. Below is my code which gives an error at line while
StandardOut has not been redirected or the process hasn't started yet.
What I want to achieve is that I want to read the output of ls into a string.
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = #"f:\plink.exe";
startinfo.Arguments = "-ssh abc#x.x.x.x -pw abc123";
Process process = new Process();
process.StartInfo = startinfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.Start();
process.StandardInput.WriteLine("ls -ltr /opt/*.tmp");
process.StandardInput.WriteLine("exit");
process.StartInfo.RedirectStandardOutput = true;
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
}
process.WaitForExit();
Console.ReadKey();
Try setting standard output redirection before starting the process.
process.StartInfo.RedirectStandardOutput = true;
process.Start();
It might be that the process already terminated when you try to read the output (dues to your "exit" command). Try the below slightly modified version where I moved your while loop after the "ls" command but before the "exit" command.
It should read the output of your "ls" command fine, but unfortunately will most probably hang at some point as you will never get EndOfStream on the StandardOutput. When there is nothing more to read, ReadLine will block until it can get read another line.
So unless you know how to detect the last line of the output generated by your command and break out of the loop after you read it, you may need to use a separate thread either for reading or for writing.
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = #"f:\plink.exe";
startinfo.Arguments = "-ssh abc#x.x.x.x -pw abc123";
Process process = new Process();
process.StartInfo = startinfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.StandardInput.WriteLine("ls -ltr /opt/*.tmp");
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
}
process.StandardInput.WriteLine("exit");
process.WaitForExit();
Console.ReadKey();

Executing batch file command within C#

I have the following code in my C# application which loaded a batch file silently using command prompt and executed and returned the result to a string:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = #"C:\files\send.bat";
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string strGetInfo = proc.StandardOutput.ReadToEnd();
strCMDOut = strGetInfo.Substring(strGetInfo.Length - 5, 3);
proc.WaitForExit();
I am trying to avoid my application going out to a different file to execute the batch file, rather I wanted to embed it inside my application. So I changed the above code to this:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "#ECHO ON java com.this.test567 send";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
proc.StartInfo = startInfo;
proc.Start();
string strGetInfo = proc.StandardOutput.ReadToEnd();
strCMDOut = strGetInfo.Substring(strGetInfo.Length - 5, 3);
When the code executes, I can see the command prompt window for a brief moment before it closes and the execution is not working correctly. How can I fix the issue?
Instead of using cmd.exe just use java directly, you should also redirect standard error and check that after the process ends.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = #"java.exe";
proc.StartInfo.Arguments = "com.this.test567";
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string strGetInfo = proc.StandardOutput.ReadToEnd();
if(string.IsNullOrEmpty(strGetInfo))
strGetInfo = proc.StandardError.ReadToEnd();
proc.WaitForExit();
Note that by calling cmd directly, you're effectively making a batch script with whatever you use for in the Arguments Property. Like a .bat file, the command window closes as soon as it's done. To fix this, add a pause command to the end.
startInfo.Arguments = "#ECHO ON java com.this.test567 send\npause";
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed to a program
so seperate commands with &
"/k #ECHO ON&java com.this.test567&send"
/k keeps a window open.
so you'll get in cmd
cmd /k #ECHO ON&java com.this.test567&send

Run CMD command without displaying it?

I have created a Process to run command in CMD.
var process = Process.Start("CMD.exe", "/c apktool d app.apk");
process.WaitForExit();
How can I run this command without displaying actual CMD window?
You can use the WindowsStyle-Property to indicate whether the process is started in a window that is maximized, minimized, normal (neither maximized nor minimized), or not visible
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
Source:
Property:MSDN
Enumartion: MSDN
And change your code to this, becaeuse you started the process when initializing the object, so the properties (who got set after starting the process) won't be recognized.
Process proc = new Process();
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.Arguments = "/c apktool d app.apk";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
There are several issues with your program, as pointed out in the various comments and answers. I tried to address all of them here.
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "apktool";
//join the arguments with a space, this allows you to set "app.apk" to a variable
psi.Arguments = String.Join(" ", "d", "app.apk");
//leave it to the application, not the OS to launch the file
psi.UseShellExecute = false;
//choose to not create a window
psi.CreateNoWindow = true;
//set the window's style to 'hidden'
psi.WindowStyle = ProcessWindowStyle.Hidden;
var proc = new Process();
proc.StartInfo = psi;
proc.Start();
proc.WaitForExit();
The main issues:
using cmd /c when not necessary
starting the app without setting the properties for hiding it
Try this :
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.WaitForExit();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

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