Files
juipnet/Infrastructure/Hncore.Infrastructure/Common/ShellHelper.cs
“wanyongkang” 40a40b6d36 忽略
2020-12-28 14:55:48 +08:00

63 lines
1.9 KiB
C#

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Hncore.Infrastructure.Common
{
public class ShellHelper
{
public static string Bash(string cmd)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
var escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
return "";
}
public static void RedirectOutputBash(string cmd)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
cmd = cmd.Replace("\"", "\\\"");
Console.WriteLine("执行命令");
Console.WriteLine(cmd);
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{cmd}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
}
}
}