Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用Process.Start启动管道和重定向命令?_C# - Fatal编程技术网

C# 如何使用Process.Start启动管道和重定向命令?

C# 如何使用Process.Start启动管道和重定向命令?,c#,C#,我正在使用System.Diagnostics.Process.Start()在Linux操作系统上远程启动命令。到目前为止,我已经能够启动简单的命令,然后读取输出。 例如,我可以执行命令echo Hello World,并读取Hello World作为其输出 以下是简化代码: public void Execute(string file, string args) { Process process = new Process { StartInfo = {

我正在使用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”,“helloworld”)

我的问题是:只要我执行简单的命令,一切都会顺利进行,但我希望使用管道和重定向来启动命令,以便对命令及其输出进行更强大的控制(而不将输出本身作为文本处理)。

那么,是否有一个解决方法(或者可能是一个特定的库)来实现这个结果?

为了在Linux中执行具有所有shell功能(包括管道、重定向等)的命令,请使用以下代码:

公共静态void ExecuteInBash(字符串命令)
{
var流程=新流程
{
StartInfo=
{
FileName=“bash”,
Arguments=“-c\”+命令+“\”,
重定向标准输出=真,
RedirectStandardError=true,
UseShellExecute=false
}
};
process.Start();

}
我认为您的代码简化了一点点。这里没有任何东西表明命令是如何在远程主机上执行的。管道本质上是数据流,如果您想控制目标进程的I/O,您将无法避开流,尤其是在跨平台工作时,由于Windows实现的流/管道与Linux不同,.NET提供了一个抽象层,为您提供了
类。您需要从进程中获取标准管道,例如
进程.StandardOutput
-因此,如果我想使用管道,我基本上需要阅读
过程。StandardOutput
然后处理我读到的内容,对吗?