Skip to content

Instantly share code, notes, and snippets.

@xoofx
Created November 11, 2019 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xoofx/b2f11b4c65e644d49e48a2fa554923a6 to your computer and use it in GitHub Desktop.
Save xoofx/b2f11b4c65e644d49e48a2fa554923a6 to your computer and use it in GitHub Desktop.
Run the same Linux command transparently from Windows (via WSL) and Linux
// Copyright 2019 - Alexandre MUTEL - License MIT
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
// Example of running a Linux command from .NET that can run transparently on Windows (via WSL) or Linux
// Assuming you are running on the same distribution, you can integrate this in your tests for example.
namespace YourNameSpace.Tests
{
public static class LinuxUtil
{
public static string ReadElf(string file, string arguments = "-W -a")
{
return RunLinuxExe("readelf", $"{file} -W -a");
}
public static string RunLinuxExe(string exe, string arguments, string distribution = "Ubuntu-18.04")
{
if (exe == null) throw new ArgumentNullException(nameof(exe));
if (arguments == null) throw new ArgumentNullException(nameof(arguments));
if (distribution == null) throw new ArgumentNullException(nameof(distribution));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
arguments = $"-d {distribution} {exe} {arguments}";
exe = "wsl.exe";
}
StringBuilder errorBuilder = null;
var process = new Process()
{
StartInfo = new ProcessStartInfo(exe, arguments)
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
RedirectStandardError = true,
},
};
process.ErrorDataReceived += (sender, args) =>
{
if (errorBuilder == null)
{
errorBuilder = new StringBuilder();
}
errorBuilder.Append(args.Data);
};
process.Start();
process.BeginErrorReadLine();
var result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new InvalidOperationException($"Error while running command `{exe} {arguments}`: {errorBuilder}");
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment