从.NET应用程序执行shell命令

RCI*_*CIX 5 .net shell console execution winforms

我需要从我的.NET应用程序执行一个shell命令,与Lua中的os.execute一点点(在该页面上稍微不同).然而粗略搜索我找不到任何东西.我该怎么做?

dat*_*ata 9

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "blah.lua arg1 arg2 arg3";
p.StartInfo.UseShellExecute = true;
p.Start();
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用P/Invoke并直接使用ShellExecute:

[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(
    IntPtr hwnd,
    string lpOperation,
    string lpFile,
    string lpParameters,
    string lpDirectory,
    ShowCommands nShowCmd);
Run Code Online (Sandbox Code Playgroud)


si6*_*618 6

如果脚本需要一段时间,您可能需要考虑异步方法.

这里有一些代码可以实现这一点,并且可以重定向标准输出以捕获在窗体上显示(WPF,Windows窗体,等等).请注意,我假设您不需要用户输入,因此它不会创建控制台窗口,这看起来更好:

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";
}
Run Code Online (Sandbox Code Playgroud)