Files
juipnet/Infrastructure/Hncore.Infrastructure/Common/ShellHelper.cs

63 lines
2.0 KiB
C#
Raw Normal View History

2020-10-07 20:25:03 +08:00
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();
}
}
}
}