从c#中的命令行调用获取标准吗?

问题描述:

现在我试图通过C#将命令传递给批处理外壳程序(.bat文件)时获取标准。我能够在cmd提示符启动时得到最初的标准(打开时显示“Hello World”),但是如果我给它一个像“ping 127.0.0.1”这样的参数,我无法获得输出结果。到目前为止,我已经尝试了两种捕获输出的方法。过程的开始保持不变。从c#中的命令行调用获取标准吗?

private void testShell(string command) 
{ 
    ProcessStartInfo pi = ProcessStartInfo(*batch shell path*, command); 
    pi.CreateNoWindow = true; 
    pi.UseShellExecute = false; 
    pi.RedirectStandardOutput = true; 
    pi.RedirectStandardInput = true; 

    Process pr = Process.Start(pi); 
//option 1 
    while(!pr.StandardOutput.EndOfStream) 
    { 
     //do something with the line 
    } 
//option 2 
    string str = ""; 
    using (System.IO.StreamReader output = pr.StandardOutput) 
    { 
     str = output.ReadToEnd(); 
    } 
//option 3 
    string output = pr.StandardOutput.ReadToEnd(); 
    //do something with the output 
} 

是否有可能将参数传递给批处理文件(这似乎是实际的问题)?

+0

因此'*批处理shell路径*'指向'.bat'文件或'cmd.exe'?我把它指向一个'.bat'文件,该文件运行'ping 127.0.0.1',我发现输出选项#3很好(使用'Console.Write(output)')。 – Quantic

+0

批处理shell,而不是默认的Windows cmd.exe。 – FyreeW

+0

什么是“批量壳”?你是把它指向一个'.exe'还是一个'.bat'文件? – Quantic

将方法附加到outputdatareceived事件。

pi.OutputDataReceived += (objectsender,DataReceivedEventArgs e) => datareceivedtwritetolog(sender, e); 

然后创建一个方法,做一些与输出:

public static void datareceivedtwritetolog(object sender, DataReceivedEventArgs e) 
{ 
    string logpath = @"c:\log-" + DateTime.Now.ToString("MMddyy") + ".txt"; 
    File.AppendAllText(logpath, e.Data + Environment.NewLine); 
} 
+0

没有看到任何输出(只是试图打印出e.Data)。 – FyreeW

+0

您需要在它之前启动proccess。然后放置:pi.StandardOutput.ReadToEnd();和pi.WaitForExit();在 –

+0

之后,我设置了上面的启动信息,然后用Process.Start启动它。然后,我在该进程上设置OutputDataReceived,并在之后调用ReadToEnd()和WaitForExit()。仍然没有看到任何输出。 – FyreeW

您不能直接传递命令作为参数。

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] 
    [[/S] [/C | /K] string] 

/C  Carries out the command specified by string and then terminates 
/K  Carries out the command specified by string but remains 

你需要写start参数为/c ping 127.0.0.1或:

ProcessStartInfo pi = ProcessStartInfo(*batch shell path *, "/c " + command); 

注意:这将打破,如果启动过程中的文件是一个批处理文件(* .bat)的形式,而不是一个shell控制台( “CMD”)


或者,可以写入命令给标准输入:

pr.StandardInput.WriteLine(command); 
// do stuffs with pr.StandardOutput 
+0

它是一个批处理文件,而不是cmd.exe。 – FyreeW

您显示的代码不会编译(它缺少new指令)。无论如何,你没有显示的批处理文件的具体内容可能会失败。下面的工作:

创建一个包含以下内容称为Example.cs文件:

然后创建一个名为ExampleBatch.cmd与文件,内容如下:

@echo off 
echo This is from the example. 
echo Param 1: [%1] 
echo Param 2: [%2] 
echo Param 3: [%3] 
echo Param 4: [%4] 
echo Param 5: [%5] 

然后编译cs文件与csc Example.cs。最后,运行Example.exe将呈现以下的输出:

-------------------- 
[THIS IS FROM THE EXAMPLE. 
PARAM 1: [A] 
PARAM 2: [B] 
PARAM 3: [C] 
PARAM 4: [D] 
PARAM 5: [] 
] 
-------------------- 

这说明,批处理文件能够捕获命令行参数,和C#程序能够捕获输出和处理它。