ASP.NET Core 如何执行 Linux shell 命令? [英] how ASP.NET Core execute Linux shell command?
本文介绍了ASP.NET Core 如何执行 Linux shell 命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 linux 上有一个 asp.net core web 应用程序,现在,我想执行 shell 命令并获取结果表单命令,我不知道,请帮帮我.
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.
有没有办法从 ASP.NET Core 应用程序中执行 linux shell 命令并将值返回到变量中?
Is there any way to execute a linux shell command from within an ASP.NET Core application and return the value into a variable?
推荐答案
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
或使用 error抛出异常代码>作为消息).
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).
这篇关于ASP.NET Core 如何执行 Linux shell 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文