如何在Xamarin.Mac中执行终端命令并读取其输出

本文关键字:命令 读取 输出 终端 执行 Xamarin Mac | 更新日期: 2024-10-20 01:05:53

我们正在编写一个Xamarin.Mac应用程序。我们需要执行一个类似"uptime"的命令,并将其输出读取到应用程序中进行解析。

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

如何在Xamarin.Mac中执行终端命令并读取其输出

在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();
  • Xamarin:https://developer.xamarin.com/api/type/System.Diagnostics.Process/

  • MSDN:https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput%28v=vs.110%29.aspx?f=255&MSPP错误=-2147217396


我的OS-XC#代码中的示例,但它是跨平台的,就像在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 ());
    }
}

下面是一个来自Xamarin论坛的例子:

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