打开命令行并在不关闭的情况下读取输出

时间:2019-02-18 13:14:13

标签: c# batch-file cmd startprocessinfo

我知道类似的问题正在这个网站上泛滥(双关语意),但是我发现在不关闭正在运行的.bat文件的情况下就无法正常工作。很抱歉,我对此并不熟练,但是我们非常感谢您的帮助。

有效方法:

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = @"C:\Temp\batch.bat";            
p.Start();          
string output = p.StandardOutput.ReadToEnd();

string DataDate =(output.Substring(output.LastIndexOf("echo date:") + 11));
string DataID1 =(output.Substring(output.LastIndexOf("echo id1:") + 10));
string DataID2 =(output.Substring(output.LastIndexOf("echo id2:") + 10));
string DataStatus =(output.Substring(output.LastIndexOf("echo status:") + 13));

这将在此处打开一个batch.bat文件,该文件打印了我可以访问的几行字符串,例如:“ echo date:15.02.2019”转到字符串DataDate。但是我想打开命令提示符并自己输入新值,而不关闭命令提示符。我正在使用按钮在上面运行该代码。我想我打开cmd进程并在每次换行时都存储它吗?如何使进程保持活动状态并使用新值更新字符串?例如,我可以输入cmd提示“回显日期:18.02.2019”,然后将保存该值。

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的意图,则希望与您的过程进行互动。因此,您的过程必须支持这种交互。例如,您的批处理文件可能会提示命令,如下所示:

@echo off

:loop
echo Enter a command:
set /p userCommand=""
%userCommand%
goto :loop

您不能使用p.StandardOutput.ReadToEnd(),因为在输出完成之前输出流还没有完成。您可以使用OutputDataReceived执行异步读取。使用上面的批处理命令尝试以下代码:

Process process = new Process();
process.StartInfo.FileName = @"C:\Temp\batch.bat";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
    // Prepend line numbers to each line of the output.
    if (!String.IsNullOrEmpty(e.Data))
    {
        Console.WriteLine(e.Data);// to see what happens
        // parse e.Data here
    }
});

process.Start();

// Asynchronously read the standard output of the spawned process. 
// This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine();

process.WaitForExit();
process.Close();

更新

要使Windows Forms应用程序正常运行,您需要将VS Project Properties -> Application -> Output TypeWindows Application更改为Console Application。或者,您可以通过编辑*.csproj文件并将<OutputType>WinExe</OutputType>替换为<OutputType>Exe</OutputType>来实现。因此,控制台可能会在所有应用程序运行期间显示,这可能对您来说是不希望的。老实说,我不知道该怎么做。