我们正在编写 Xamarin.Mac 应用程序。我们需要执行一个像“uptime”这样的命令,并将它的输出读入应用程序进行解析。

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

最佳答案

在 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&MSPPError=-2147217396

  • 来自我的 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 ());
        }
    }
    

    关于c# - 如何在 Xamarin.Mac 中执行终端命令并读入其输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36751590/

    10-15 12:07