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

3
我们正在编写一款Xamarin.Mac应用程序。我们需要执行类似于“uptime”的命令,并将其输出读入应用程序以进行解析。
这个能做到吗?在Swift和Objective-C中有NTask,但我似乎找不到任何C#的示例。
2个回答

3
在Mono/Xamarin.Mac下,您可以使用“标准”的.Net/C# Process类,因为该进程会被映射到底层操作系统(对于Mono、MonoMac和Xamarin.Mac来说是OS-X,在*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
这里提供了Xamarin和MSDN的链接,它们分别是关于System.Diagnostics.Process类和ProcessStartInfo.RedirectStandardOutput属性的。
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 ());
    }
}

0

这里是一个示例,取自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 ();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接