Running exe with parameters doesn't work - c#

var p = Process.Start(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");
var err = p.StandardError.ReadToEnd();
var msg = p.StandardOutput.ReadToEnd();
lblStatusResponse.Text = "Err: " + err + "Msg: " + msg;
Why is my code not working?
I getting error:
System.InvalidOperationException: StandardError has not been redirected.
But when I add following:
p.StartInfo.RedirectStandardError = true;
var p = Process.Start(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");)
it still gets the same error.
The main problem is that I wanna execute a exe with arguments, but I can't get it to work.

The following code generates a new p, this ignoring the settings you change in the previous instance:
var p = Process.Start(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");)
So it doesn't really matter whether you initialize p like this
p.StartInfo.RedirectStandardError = true;
or not.
What you need to do
You need to create a ProcessStartInfo object, configure it and then pass it to Process.Start.
ProcessStartInfo p = new ProcessStartInfo(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");
p.UseShellExecute = false;
p.RedirectStandardError = true;
p.RedirectStandardOutput = true;
Process proc = Process.Start(p);
var err = proc.StandardError.ReadToEnd();
var msg = proc.StandardOutput.ReadToEnd();

Taken from MSDN: https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput(v=vs.110).aspx
The StandardOutput stream has not been defined for redirection; ensure ProcessStartInfo.RedirectStandardOutput is set to true and ProcessStartInfo.UseShellExecute is set to false.
So remember to set those flags as instructed by MS.

Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Arguments = "/C " + command; //Enter your own command
proc.Start();
string output =proc.StandardOutput.ReadToEnd();

I know this is not the same code you have but this is was the only working code I have , that will run external command/process in C# , and return all of it output/errors to the application main window
public void Processing()
{
//Create and start the ffmpeg process
System.Diagnostics.ProcessStartInfo psi = new ProcessStartInfo("ffmpeg")
{ // this is fully command argument you can make it according to user input
Arguments = "-y -i '/mnt/Disk2/Video/Antina03.jpg' pp.mp4 ",
RedirectStandardOutput = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError=true,
RedirectStandardInput=true
};
System.Diagnostics.Process ischk;
ischk = System.Diagnostics.Process.Start(psi);
ischk.WaitForExit();
////Create a streamreader to capture the output of ischk
System.IO.StreamReader ischkout = ischk.StandardOutput;
ischk.WaitForExit();
if (ischk.HasExited) // this condition very important to make asynchronous output
{
string output = ischkout.ReadToEnd();
out0 = output;
}
/// in case you got error message
System.IO.StreamReader iserror = ischk.StandardError;
ischk.WaitForExit();
if (ischk.HasExited)
{
string output = iserror.ReadToEnd();
out0 = output;
}
}
if you want to run this process just call the function Processing() BTW out0 are global variable so it can use out the function .
credit
I'm using MonoDevlop "C# devloping tool on Linux " and I get the output this way :-
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
Processing();
textview2.Buffer.Text = out0;
}

Related

How to get SVN Commit log using c# Process

I need to get the commit log by date for a svn project using C# application i.e if we have provided the URl , start and end date , we should use the svn.exe in a process to get log details
I have use the command svn log -r {"2007-07-07"}:{2019-11-08} to get the log in command prompt.
SourcePath = args[0]; // URL link
var startDate = args[1];
var endDate = args[2];
var svnSource = args[3]; // svn.exe location in my machine
var cmd1 = "cd /";
var cmd2 = "c:";
var cmd3 = string.Concat("cd ", svnSource);
var cmd4 = string.Concat("svn log ", SourcePath, " -r {", startDate, "}:{", endDate, "}");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "svn.exe";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(cmd1);
process.StandardInput.WriteLine(cmd2);
process.StandardInput.WriteLine(cmd3);
process.StandardInput.WriteLine(cmd4);
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
if (!process.HasExited)
{
}
}
}
I expect the result in the string "line" with all log values but i am getting actual output value as empty. breakpoint does not hit the "while (!process.StandardOutput.EndOfStream)" part itself while debugging.
How to resolve this ? what am i doing wrong here?
First of all, svn.exe will not interpret commands like that, so instead you should start a shell like cmd.exe.
If you're supplying a URL for your SourcePath then svn can run from anywhere from cmd, so you don't need the first 3 commands at all: cmd1, cmd2, cmd3.
That being said, you're not gonna need the svnSource variable either.
Of course, you can cd to the root directory to make your output look cleaner.
So these are the modifications I made to your code:
var SourcePath = args[0]; // URL link
var startDate = args[1];
var endDate = args[2];
var cmd1 = "cd c:\\";
var cmd2 = string.Concat("svn log ", SourcePath, " -r {", startDate, "}:{", endDate, "}");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(cmd1);
process.StandardInput.WriteLine(cmd2);
// It's always a good idea to close your standard input when you're not gonna need it anymore,
// otherwise the process will wait indefinitely for any input and your while condition will never
// be true or in other words it will become an infinite loop...
process.StandardInput.Close();
string result = string.Empty; // for storing the svn commit log
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
if (!process.HasExited)
{
result += line + Environment.NewLine;
}
}
}

How can i execute msg.exe by C# in windows?

Is there a way to display the windows popup msg by using C#?
I mean by using the windows msg.exe program that can be used in cmd, for example:" msg * Hello "
PD: I know that i can use MessageBox.Show() instead. But i want to know if this is possible :(
I wrote 2 ways to do it but none worked:
Process.Start("cmd.exe","/C msg * Hello");
and...
Process cmd = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C msg * Hello",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}
};
cmd.Start();
Did you try adding msg.exe directly?
Process cmd = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #"msg.exe",
Arguments = #"* /v Hello",
WorkingDirectory = Environment.SystemDirectory;
WindowStyle = ProcessWindowStyle.Normal
}
};
cmd.Start();
I encountered the same problem.
This was because the project was configured as "AnyCPU" but the "Prefer 32-bit" option was checked in the "Build" tab of the project configuration. Uncheck that option and the problem will disappear.
Edit: personnaly, I use the following function to locate the binary according to the executable and OS platform (32/64 bits):
public static bool LocateMsgExe(out string returnedMsgPath)
{
returnedMsgPath = null;
string[] msgPaths = new string[] { Environment.ExpandEnvironmentVariables(#"%windir%\system32\msg.exe"),
Environment.ExpandEnvironmentVariables(#"%windir%\sysnative\msg.exe") };
foreach (string msgPath in msgPaths)
{
if (File.Exists(msgPath))
{
returnedMsgPath = msgPath;
return true;
}
}
return false;
}
And for invoking it :
if (LocateMsgExe(out string strMsgPath))
{
Process.Start(strMsgPath, "* \"Hello world!\"");
}
Regards,
damien.
This is my solution. It consists of a webpage (.aspx) with a listbox (lstComputers), a textbox (txtMessageToSend), a dropdownlist to select the OU that contains the computers that will receive the message and a button (btnSendMessage).
This is the code for btnSendMessage on the aspx.cs
protected void btnSendMessage_Click(object sender, EventArgs e)
{
string searchbase = ddlZaal.SelectedItem.Text; //This is a dropdownlist to select an OU
DirectoryEntry entry = new DirectoryEntry("LDAP://OU=" + searchbase + ",OU=YourOU,OU=YourSubOU," + Variables.Domain + ""); //Variables.Domain is specified in the Web.config
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)");
foreach (SearchResult result in mySearcher.FindAll())
{
DirectoryEntry directoryObject = result.GetDirectoryEntry();
string computernaam = directoryObject.Properties["Name"].Value.ToString();
lstComputers.Items.Add(computernaam); //This is a listbox that shows the computernames. To each computer a message is sent.
string pingnaam = computernaam + "dns.suffix"; //Might be necessary for connecting to the computes in the domain
string MessageToSend = txtMessageToSend.Text; //The text in this textbox will be the messagetext
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo(#"C:\inetpub\wwwroot\PsExec.exe"); //Location of PsExec.exe on the webserver that hosts the web-application.
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Minimized;
psi.CreateNoWindow = true;
psi.Arguments = "/accepteula -s -i \\\\" + pingnaam + " cmd /c msg.exe * " + MessageToSend;
process.StartInfo = psi;
process.Start();
}
}

Read from an external program/console

I have a problem, I need to execute a console program and I have to show the output information of that console on my program. I have a string variable called "result" that have to storage that information, but is always null and I don't know why. Can anyone help me? I put the code below:
Process p = new Process();
p.StartInfo.FileName = "python";
p.StartInfo.Arguments = #"C:\Users\xxx\xxx\xxx\xxx_\xxx yyy\zzz.py " + path;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
StreamReader sr = p.StandardOutput;
p.WaitForExit();
string result = sr.ReadToEnd();
sr.Close();
textBox1.Text = result;
On the console, I recieve 8382 JGK, for example, but my result variable is always "".
You could try something like this
StreamReader sr = p.StandardOutput;
p.WaitForExit();
char[] result = new char[p.Length]; //or sr.BaseStream.Length
sr.Read(result,0,(int)p.Length); // again or sr.BaseStream.Length
And see if result array contains anything.
I solve it! The problem was on the file's path. I have to put it on the same folder as the ".py" file and it works fine. I add the correct piece of code:
string python = #"C:\xxx\python.exe";
string myPythonApp = "program.py";
string x = #"file.jpg";
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.Arguments = myPythonApp + " " + x;
Process myProcess = new Process();
myProcess.StartInfo = myProcessStartInfo;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
myProcess.WaitForExit();
myProcess.Close();
textBox1.Text = myString;

C# Winforms and command line batch files

I have this running from my c# winforms app:
string ExecutableFilePath = #"Scripts.bat";
string Arguments = #"";
if (File.Exists(ExecutableFilePath )) {
System.Diagnostics.Process.Start(ExecutableFilePath , Arguments);
}
When that runs I get to see the cmd window until it finishes.
Is there a way to get that to run without showing it to the user?
You should use ProcessStartInfo class and set the following properties
string ExecutableFilePath = #"Scripts.bat";
string Arguments = #"";
if (File.Exists(ExecutableFilePath ))
{
ProcessStartInfo psi = new ProcessStartInfo(ExecutableFilePath , Arguments);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process.Start(psi);
}

Invalid option file options: pad=oper

Getting this error: Invalid option file options on trying to invoke Astyle via C#
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + #"\Astyle.exe";
//strCommandParameters are parameters to pass to program
//pProcess.StartInfo.Arguments = "--style=ansi --recursive "+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)+"/*.cpp";
pProcess.StartInfo.Arguments = " options=none test.cpp";
//pProcess.StartInfo.Arguments = " -h";
pProcess.StartInfo.UseShellExecute = false;
//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.RedirectStandardError = true;
//Optional
pProcess.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//Start the process
pProcess.Start();
//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();
string strError = pProcess.StandardError.ReadToEnd();
//Wait for process to finish
pProcess.WaitForExit();
If you take a look at this link the correct syntax seems to be
--options=none

Categories