簡體   English   中英

如何使用Process.Start啟動管道並重定向命令?

[英]How can I launch pipes and redirects commands with Process.Start?

我正在使用System.Diagnostics.Process.Start()在Linux操作系統上遠程啟動命令。 到目前為止,我已經能夠啟動簡單的命令,然后讀取輸出。
例如,我可以執行命令echo Hello World並讀取Hello World作為其輸出。

這是簡化的代碼:

public void Execute(string file, string args) {
    Process process = new Process {
        StartInfo = {
            FileName = file,
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false
        }
    };
    process.Start();
}

為了更清楚,我使用上面的代碼: Execute("echo", "Hello World");

這是我的問題:只要我執行簡單的命令一切順利,但我想用管道和重定向啟動命令,以便對命令及其輸出有更強的控制(無需將輸出本身作為文本處理)。
那么,是否有解決方法(或者可能是特定的庫)來實現這一結果?

為了在Linux中執行具有所有shell功能(包括管道,重定向等)的命令,請使用以下代碼:

public static void ExecuteInBash(string command)
{
    var process = new Process
    {
        StartInfo = 
        {
            FileName = "bash",
            Arguments = "-c \"" + command + "\"",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false
        }
    };
    process.Start();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM