【问题标题】:How to execute a terminal command in Xamarin.Mac and read-in its output如何在 Xamarin.Mac 中执行终端命令并读入其输出
【发布时间】:2016-08-13 14:11:57
【问题描述】:

我们正在编写 Xamarin.Mac 应用程序。我们需要执行“uptime”之类的命令,并将其输出读入应用程序进行解析。

可以这样做吗?在 Swift 和 Objective-C 中有 NTask,但我似乎无法在 C# 中找到任何示例。

【问题讨论】:

    标签: c# xamarin terminal output


    【解决方案1】:

    在 Mono/Xamarin.Mac 下,您可以将“标准”.Net/C# 进程类映射到底层操作系统(OS-X 用于 Mono、MonoMac 和 Xamarin.Mac,Mono 用于 *nix) .

    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "Write500Lines.exe";
    p.Start();
    
    // To avoid deadlocks, always read the output stream first and then wait.
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    

    我的 OS-X C# 代码中的示例,但它是跨平台的,因为它在 Windows/OS-X/Linux 下工作,只是您正在运行的可执行文件跨平台更改。
    var startInfo = new ProcessStartInfo () {
        FileName = Path.Combine (commandPath, command),
        Arguments = arguments,
        UseShellExecute = false,
        CreateNoWindow = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        RedirectStandardInput = true,
        UserName = System.Environment.UserName
    };
    
    using (Process process = Process.Start (startInfo)) { // Monitor for exit}
        process.WaitForExit ();
        using (var output = process.StandardOutput) {
            Console.Write ("Results: {0}", output.ReadLine ());
        }
    }
    

    【讨论】:

      【解决方案2】:

      这是取自Xamarin forum:的示例

      var pipeOut = new NSPipe ();
      
      var t =  new NSTask();
      t.LaunchPath = launchPath;
      t.Arguments = launchArgs;
      t.StandardOutput = pipeOut;
      
      t.Launch ();
      t.WaitUntilExit ();
      t.Release ();
      
      var result = pipeOut.ReadHandle.ReadDataToEndOfFile ().ToString ();
      

      【讨论】:

        猜你喜欢
        • 2016-03-16
        • 1970-01-01
        • 1970-01-01
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        • 2021-03-27
        • 1970-01-01
        • 2022-01-06
        相关资源
        最近更新 更多