15

I have an ASP.NET Core web app on Linux. I want to execute shell commands and get result from commands.

Is there a way to execute a Linux shell command from within an ASP.NET Core application and return the value into a variable?

2

1 Answer 1

14
string RunCommand(string command, string args)
{
    var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = command,
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
    process.Start();
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();
    process.WaitForExit();

    if (string.IsNullOrEmpty(error)) { return output; }
    else { return error; }
}

// ...

string rez = RunCommand("date", string.Empty);

I would also add some way to tell if the string returned is an error or just a "normal" output (return Tuple<bool, string> or throw exception with error as a message).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.