Skip to main content

Helper function to retrieve the output of a specified command.

using System.Diagnostics;

public static class ShellExecutor
{
    public static string? GetOutput(string command, string? args = null)
    {
        var info = new ProcessStartInfo
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true,
            FileName = command,
            Arguments = args ?? string.Empty
        };

        using (var process = Process.Start(info))
        {
            var res = process?.StandardOutput.ReadToEnd();
            return res;
        }
    }
}

// --------------------------------
// Usage
// --------------------------------

var driveInfo = ShellExecutor.GetOutput("df", string.Format("-P {0}", "/path/to/directory"));