Run a shell command from a .NET application

I need to execute a shell command from my .NET application, unlike os.execute (a bit down on this page) in Lua . However, with a cursory search, I could not find anything. How to do it?

+5
shell console winforms execution
source share
3 answers
 System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "blah.lua arg1 arg2 arg3"; p.StartInfo.UseShellExecute = true; p.Start(); 

Another way would be to use P / Invoke and use ShellExecute directly:

 [DllImport("shell32.dll")] static extern IntPtr ShellExecute( IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd); 
+9
source share

Maybe you should consider an asynchronous approach if the script takes some time.

Here's some code that does this, redirects the standard output to display for display on the form ( WPF , Windows Forms , whatever). Note that I assume that you do not need user input, so it does not create a console window that looks better:

 BackgroundWorker worker = new BackgroundWorker(); ... // Wire up event in the constructor or wherever is appropriate worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); ... // Then to execute your script worker.RunWorkerAsync("somearg anotherarg thirdarg"); void worker_DoWork(object sender, DoWorkEventArgs e) { StringBuilder result = new StringBuilder(); Process process = new Process(); process.StartInfo.FileName = "blah.lua"; process.StartInfo.Arguments = (string)e.Argument; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.CreateNoWindow = true; process.Start(); result.Append(process.StandardOutput.ReadToEnd()); process.WaitForExit(); e.Result = result.AppendLine().ToString(); } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Result != null) console.Text = e.Result.ToString(); else if (e.Error != null) console.Text = e.Error.ToString(); else if (e.Cancelled) console.Text = "User cancelled process"; } 
+6
source share

In C #, there is an easy way to handle this. Using the System.Diagnostics namespace, there is a class for handling spawning processes.

 System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "App.exe"; process.StartInfo.Arguments = "arg1 arg2 arg3"; process.Start(); Console.WriteLine(process.StandardOutput.ReadToEnd(); 

There are additional options for handling things like not creating a console window, redirecting input or output, and much more that you need.

+2
source share

All Articles