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

How to execute a terminal command in Xamarin.Mac and read-in its output

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

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

在 Mono/Xamarin.Mac 下,您可以将“标准”.Net/C# 流程 Class 作为流程映射到底层 OS (OS-X 对于 Mono,MonoMac 和 Xamarin.Mac,以及对于 *nix 的 Mono。

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 下工作,只是你是 [=39] 的可执行文件=] 跨平台变化。
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 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 ();