Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

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

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#.

Upvotes: 3

Views: 3809

Answers (2)

SushiHangover
SushiHangover

Reputation: 74194

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();

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 ());
    }
}

Upvotes: 3

Giorgi
Giorgi

Reputation: 30883

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 ();

Upvotes: 0

Related Questions