如何在DotNet Core中运行Bash命令

8
我正在使用 dotnet-core 1.1,CentOS Bash。有没有一种方法可以运行 grep 或 wget 并检索结果?类似于 Windows 中的 cmd,但我需要实时查看日志文件,像这样:

System.Diagnostics.Process.Start("notepad.exe")


1
https://www.nuget.org/packages/runtime.linux.System.Diagnostics.Process/4.1.0-beta-23516是否添加了任何内容以捕获结果? - Derek Beattie
你可以在这里找到有用的信息:https://dev59.com/cKXja4cB1Zd3GeqPRniO - Harit Kumar
2个回答

8
您可以启动进程来进行 grep 并检索结果,可以参考以下代码。
            System.Diagnostics.ProcessStartInfo procStartInfo;                
            procStartInfo = new System.Diagnostics.ProcessStartInfo("/bin/bash", "-c \"cat myfile.log | grep -a 'dump f'\""); 
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.RedirectStandardError = true;
            procStartInfo.UseShellExecute = false;

            procStartInfo.CreateNoWindow = true;

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();
            // Get the output into a string
            result = proc.StandardOutput.ReadToEnd();

3

我相信在System.Diagnostics.Process nuget包中的 System.Diagnostics.Process.Start(..) 方法可以将 ProcessStartInfo 类型作为其中一个重载。当该类型设置为 true 时,以下属性将重定向日志到由 System.Diagnostics.Process 返回的 Process 类型中的流中:

var proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() {
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    RedirectStandardError = true

} );

proc.StandardError //stream with stderror
proc.StandardInput //stream with stdin
proc.StandardOutput //stream with stdout

我还制作了一个软件包,可以轻松地在Mac/Win/Linux上打开文件,基本上它抽象了xdg-open(Ubuntu)、open(Mac)和cmd.exe(Win),这样你就不必再去考虑它们了。以下是该软件包的链接:https://github.com/TerribleDev/Opener.Net

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接