【问题标题】:Execute a shell command from a .NET application从 .NET 应用程序执行 shell 命令
【发布时间】:2009-11-30 02:11:30
【问题描述】:

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

【问题讨论】:

    标签: .net winforms console execution shell


    【解决方案1】:
    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);
    

    【讨论】:

    • 即将blah.lua somearg anotherarg thirdarg 放在控制台命令中。
    【解决方案2】:

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

    这里有一些代码可以做到这一点,并重定向标准输出以捕获以显示在表单上(WPFWindows 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";
    }
    

    【讨论】:

    • +1 用于正确使用后台工作者并且不阻塞整个线程。更好的用户体验!
    【解决方案3】:

    在 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();
    

    还有其他参数可以处理诸如不创建控制台窗口、重定向输入或输出以及您需要的大多数其他事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-28
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 2015-05-01
      • 1970-01-01
      相关资源
      最近更新 更多