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

两盒软妹~` 提交于 2019-12-12 17:15:06

问题


We are writing a Xamarin.Mac application. We need to execute a command like "uptime" and read it's output into an application to parse.

Could this be done? In Swift and Objective-C there is NTask, but I don't seem to be able to find any examples in C#.


回答1:


Under Mono/Xamarin.Mac, you can the "standard" .Net/C# Process Class as the Process gets mapped to the underlaying OS (OS-X For Mono, MonoMac and Xamarin.Mac, and 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();
  • 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


Example from my OS-X C# code, but it is cross-platform as it works as is under Windows/OS-X/Linux, just the executable that you are running changes across the platforms.
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 ());
    }
}



回答2:


Here is an example taken from 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 ();


来源:https://stackoverflow.com/questions/36751590/how-to-execute-a-terminal-command-in-xamarin-mac-and-read-in-its-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!