我需要从我的 .NET 应用程序中执行一个 shell 命令,这与Luaos.execute
中的(在该页面上的一点点)不同。然而,粗略的搜索我找不到任何东西。我该怎么做?
问问题
9354 次
3 回答
9
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "blah.lua arg1 arg2 arg3";
p.StartInfo.UseShellExecute = true;
p.Start();
另一种方法是使用P/Invoke并直接使用 ShellExecute:
[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(
IntPtr hwnd,
string lpOperation,
string lpFile,
string lpParameters,
string lpDirectory,
ShowCommands nShowCmd);
于 2009-11-30T02:15:15.157 回答
6
如果脚本需要一段时间,您可能需要考虑异步方法。
这是一些执行此操作的代码,并重定向标准输出以捕获以显示在表单(WPF,Windows Forms等)上。请注意,我假设您不需要用户输入,因此它不会创建看起来更好的控制台窗口:
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";
}
于 2009-11-30T02:57:00.927 回答
2
在 C# 中有一个简单的方法来处理这个问题。使用 System.Diagnostics 命名空间,有一个类来处理生成过程。
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();
还有其他参数可以处理诸如不创建控制台窗口、重定向输入或输出以及您需要的大多数其他事情。
于 2009-11-30T02:33:44.860 回答