【问题标题】:how ASP.NET Core execute Linux shell command?ASP.NET Core 如何执行 Linux shell 命令?
【发布时间】:2017-04-07 10:41:25
【问题描述】:

我有一个 linux 上的 asp.net core web 应用程序,现在,我想执行 shell 命令并获取结果形式的命令,我不知道,请帮助我。

有没有办法从 ASP.NET Core 应用程序中执行 linux shell 命令并将值返回到变量中?

【问题讨论】:

标签: c# asp.net .net asp.net-core .net-core


【解决方案1】:
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 抛出异常作为消息)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2019-11-06
    • 2015-01-03
    • 1970-01-01
    相关资源
    最近更新 更多