我在Linux上有一个ASP.NET Core Web应用程序。我想执行shell命令并获取命令的结果。
是否有一种方法可以从ASP.NET Core应用程序内部执行Linux shell命令并将值返回到变量中?
我在Linux上有一个ASP.NET Core Web应用程序。我想执行shell命令并获取命令的结果。
是否有一种方法可以从ASP.NET Core应用程序内部执行Linux shell命令并将值返回到变量中?
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);
我还想添加一种方法来判断返回的字符串是错误的还是正常的输出(返回Tuple<bool, string>
或抛出异常,并将error
作为消息)。
Process.Execute
? - Lex Li