C# 如何在Xamarin.Mac中执行终端命令并读取其输出
我们正在编写一个Xamarin.Mac应用程序。我们需要执行像“正常运行时间”这样的命令,并将其输出读入应用程序进行解析C# 如何在Xamarin.Mac中执行终端命令并读取其输出,c#,xamarin,terminal,output,C#,Xamarin,Terminal,Output,我们正在编写一个Xamarin.Mac应用程序。我们需要执行像“正常运行时间”这样的命令,并将其输出读入应用程序进行解析 这能做到吗?在Swift and Objective-C中有NTask,但我似乎在C#中找不到任何例子。在Mono/Xamarin.Mac下,当进程映射到底层操作系统时,可以使用“standard.Net/C#Process类(OS-X代表Mono、MonoMac和Xamarin.Mac,Mono代表*nix) 沙马林: MSDN: 来自我的OS-XC#代码的示例,
这能做到吗?在Swift and Objective-C中有NTask,但我似乎在C#中找不到任何例子。在Mono/Xamarin.Mac下,当进程映射到底层操作系统时,可以使用“standard.Net/C#Process类(OS-X代表Mono、MonoMac和Xamarin.Mac,Mono代表*nix)
- 沙马林:
- MSDN:
来自我的OS-XC#代码的示例,但它是跨平台的,就像在Windows/OS-X/Linux下一样,只是跨平台运行更改的可执行文件。
下面是一个例子
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();
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 ());
}
}
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 ();