Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how ASP.NET Core execute Linux shell command?

i have a asp.net core web app on linux ,now, i want to execulate shell command and get result form command , i have no idea , please help me.

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

like image 843
bin Avatar asked Nov 23 '16 12:11

bin


1 Answers

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

like image 188
retif Avatar answered Oct 05 '22 11:10

retif