I have a windows console app (that accepts parameters) and runs a process.
I was wondering if there was any way to run this app from within a windows form button click event. I would like to pass an argument to it as well.
Thanks
Just use System.Diagnostics.Process.Start with the path to the console application, and the parameters as the second argument.
Assuming you have a form with a multiline textbox called txtOutput.....
private void RunCommandLine(string commandText)
{
try
{
Process proc = new Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/c " + commandText;
txtOutput.Text += "C:\\> " + commandText + "\r\n";
proc.Start();
txtOutput.Text += proc.StandardOutput.ReadToEnd().Replace("\n", "\r\n");
txtOutput.Text += proc.StandardError.ReadToEnd().Replace("\n", "\r\n");
proc.WaitForExit();
txtOutput.Refresh();
}
catch (Exception ex)
{
txtOutput.Text = ex.Message;
}
}
You'll want to use System.Diagnostics.Process
Related
I would like to use Powershell to Start an application with some options of Start-Process as the code and then close the application after the process is done. The process is to measure some signals.
At first, this process is done by the C# code but I think this function can be converted to Powershell. However I dont' know how to do that, especially, with the Process.Exited and Process.EnableRaisingEvents.
Please help me.
Thank you in advance.
public void Execute_process(string console_path, string arg1)
{
try
{
//プロセス作成
p = new Process();
p.StartInfo.FileName = console_path + "\\" + "IQfactRun_Console.exe";
//p.StartInfo.Verb = "RunAs";
p.StartInfo.Arguments = " -run " + ini["IQFACT", "flow_folder"] + "\\" + arg1;
Debug.WriteLine("arg:" + " -run " + ini["IQFACT", "flow_folder"] + "\\" + arg1);
p.StartInfo.CreateNoWindow = false;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
p.StartInfo.UseShellExecute = true;
p.StartInfo.WorkingDirectory = ini["IQFACT", "Console_file"];
p.StartInfo.RedirectStandardError = false;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardInput = false;
p.Exited += new EventHandler(Process_exited);
p.EnableRaisingEvents = true;
//プロセス実行状態に設定
run_status = true;
//外部プロセス起動
p.Start();
}
catch (Exception ex)
{
Debug.WriteLine("例外発生:" + ex);
}
}
I am trying to retrieve console output of a python script by running that script in c# console application. but I don't know what I am doing wrong as I am not able to read any output. Please help me.
This is my code sample:
Process proc = new Process();
try
{
proc.StartInfo.FileName = "C:\\Program Files\\Python36\\python.exe";
proc.StartInfo.Arguments = "\"E:/Database/Python Scripts/TestFile.py\" \"E:/Database/Testing.db\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.EnableRaisingEvents = true;
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
Console.WriteLine("line:" + line);
}
Console.WriteLine("The End");
Console.ReadLine();
}
catch(Exception ex)
{
Console.WriteLine("Error:{0}, Detail: {1}", ex.Message, ex.StackTrace);
Console.ReadLine();
}
finally
{
//Console.ReadLine();
proc.Close();
proc.Dispose();
}
First you need to set proc.StartInfo.RedirectStandardOutput = false; to true
then you need to listen for the output event
proc.StartInfo.FileName = "C:\\Program Files\\Python36\\python.exe";
proc.StartInfo.Arguments = "\"E:/Database/Python Scripts/TestFile.py\" \"E:/Database/Testing.db\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.EnableRaisingEvents = true;
proc.OutputDataReceived+= ProcessOutputHandler;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
private void ProcessOutputHandler(object sender, DataReceivedEventArgs e)
{
//get the data using e.Data
}
You can do the same thing for the ErrorOutput Since they are seperate streams you can get. To listen for error just add an event listener for proc.ErrorDataReceived+= ProcessErrorOutputHandler;
I am creating WinForm application which starts a process with redirection. I am using Async method:
proc = new Process();
proc.StartInfo.FileName = commandLocation + procesName;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.WorkingDirectory = workingDirectory;
proc.StartInfo.CreateNoWindow = true;
proc.OutputDataReceived += (sender, args) => AppendLine(args.Data);
proc.ErrorDataReceived += (sender, args) => AppendLine(args.Data);
proc.Start();
proc.StandardInput.WriteLine(inputText);
proc.BeginOutputReadLine();
while (!proc.HasExited) //Instead of WaitForExit
{
Thread.Sleep(100); //Because of CPU usage
Application.DoEvents();
}
Here is AppendLine method for displaying output to richtextbox:
private void AppendLine(string line)
{
if (richTextBoxOutput.InvokeRequired)
{
Action act = () =>
{
this.richTextBoxOutput.AppendText(line + Environment.NewLine);
};
this.BeginInvoke(act);
}
else
{
richTextBoxOutput.AppendText(line + Environment.NewLine);
}
}
Everything works well. But when I run a console application that needs input (for example Console.ReadLine()), my application crashes link (not responding). How can I send input to the redirected console application throughout its run?
I want to import a csv file to mongodb by using mongoimport in C#. So I implement this method
public bool importCSV(string filepath, string db, string collectionName){
string result="";
try
{
ProcessStartInfo procStart = new ProcessStartInfo("cmd", "C:/MongoDB/Server/3.0/bin/mongoimport -d " + db + " -c " + collectionName + " --type csv --file " + filepath );
procStart.RedirectStandardOutput = true;
procStart.CreateNoWindow = false;
Process proc = new Process();
proc.StartInfo = procStart;
proc.Start();
result += proc.StandardOutput.ReadToEnd();
}
catch(Exception e){
Console.WriteLine(e.ToString());
}
if (!result.Equals("")){
return true;
}
return false;
}
When I run command itself, I can import file to MongoDB. But by using C#, method returns false.
Can anyone help me to solve this problem?
SOLUTION!!!
public bool importCsv(string filepath, string collectionName){
string result ="";
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:/MongoDB/Server/3.0/bin/mongoimport.exe";
startInfo.Arguments = #" -d test -c " + collectionName + " --type csv --file " + filepath + " --headerline";
Process proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
result += "ddd";
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
if (!result.Equals(""))
{
return true;
}
return false;
}
try something like this:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
result+=e.Data;
}
});
process.Start();
// Asynchronously read the standard output of the spawned process.
// This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine();
process.WaitForExit();
process.Close();
I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered.
I am using C# and .NET Framework 3.5sp1. Any help much appreciated.
Thanks,
Bryan
public partial class CommandLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = #"c:\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = "dir";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Response.Write(output);
}
}
You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits.
In order to have cmd.exe run a program and then quit, you need to send it the syntax "/c [command]". Try running the same code with the line
si.StartInfo.Arguments = "dir";
replaced with
si.StartInfo.Arguments = "/c dir";
and see if it works.
Most likely your problem is with the permissions. The user under which ASP.NET process runs is with very limited rights.
So, either you have to set the proper permissions for that user, or run ASP.NET under some other user.
This hides a security risks though, so you have to be very careful.
This is madness! Use the System.IO namepace to create your file list from inside your C# program! It's very easy to do; although this technique also has authorization issues.
Use System.Diagnostics.Process.
Here is some ASP.NET code shelling out to run subversion commands on the command line.
///////////////////////////////////////////////////////////////////////
public static string run_svn(string args_without_password, string svn_username, string svn_password)
{
// run "svn.exe" and capture its output
System.Diagnostics.Process p = new System.Diagnostics.Process();
string svn_path = Util.get_setting("SubversionPathToSvn", "svn");
p.StartInfo.FileName = svn_path;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
args_without_password += " --non-interactive";
Util.write_to_log ("Subversion command:" + svn_path + " " + args_without_password);
string args_with_password = args_without_password;
if (svn_username != "")
{
args_with_password += " --username ";
args_with_password += svn_username;
args_with_password += " --password ";
args_with_password += svn_password;
}
p.StartInfo.Arguments = args_with_password;
p.Start();
string stdout = p.StandardOutput.ReadToEnd();
p.WaitForExit();
stdout += p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
if (error != "")
{
Util.write_to_log(error);
Util.write_to_log(stdout);
}
if (error != "")
{
string msg = "ERROR:";
msg += "<div style='color:red; font-weight: bold; font-size: 10pt;'>";
msg += "<br>Error executing svn.exe command from web server.";
msg += "<br>" + error;
msg += "<br>Arguments passed to svn.exe (except user/password):" + args_without_password;
if (error.Contains("File not found"))
{
msg += "<br><br>***** Has this file been deleted or renamed? See the following links:";
msg += "<br><a href=http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html>http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html</a>";
msg += "<br><a href=http://subversion.open.collab.net/articles/best-practices.html>http://subversion.open.collab.net/articles/best-practices.html</a>";
msg += "</div>";
}
return msg;
}
else
{
return stdout;
}
}