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

标签 c# xamarin terminal output

我们正在编写 Xamarin.Mac 应用程序。我们需要执行诸如“正常运行时间”之类的命令,并将其输出读取到应用程序中进行解析。

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

最佳答案

在 Mono/Xamarin.Mac 下,您可以将“标准”.Net/C# 进程类映射到底层操作系统(OS-X For Mono、MonoMac 和 Xamarin.Mac,以及 Mono for *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();

来 self 的 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/

相关文章:

c# - Sql Injection - 以下内容是否容易受到攻击?

c# - 为什么 TreeView 控件会折叠所有子节点?

c# - 适用于 Windows Phone(8.1 和 10)平台的 Xamarin Forms 中的滑动手势识别器

sqlite - Xamarin Crash on iOS only on SQLite update call for model

macos - 安装 tensorflow

c# - 如何在 ListView 中显示对象列表属性

c# - Sitecore LinkManager GetItemUrl。为什么这么棘手?

xaml - 使用 StackLayout 进行标签包装

linux - 我如何在使用“ls -la”时隐藏终端中链接文件夹的原始目录

python - 您是否运行python setup.py开发?