我在 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
作为消息)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)