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

标签 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” goes to string DataDate。但是我想打开命令提示符并自己键入新值而不关闭命令提示符。我正在使用一个按钮来运行上面的代码。我想我打开 cmd 进程并在每次有新行时存储它?我怎样才能使进程保持事件状态并使用更新的值更新我的字符串?例如,我可以在 cmd 提示符中输入“echo date: 18.02.2019”,然后该值将被保存。

最佳答案

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

@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 窗体应用正常工作,您需要在 VS 中进行更改 Project Properties -> Application -> Output Type来自 Windows ApplicationConsole Application .或者您可以通过编辑 *.csproj 来完成文件并替换 <OutputType>WinExe</OutputType>通过 <OutputType>Exe</OutputType> .因此,控制台将在所有应用程序运行期间显示,这可能是您不希望看到的。老实说,我不知道如何用其他方式做到这一点。

关于c# - 打开命令行并在不关闭的情况下读取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54748161/

相关文章:

string - 批处理文件 : How to replace "=" (equal signs) and a string variable?

c# - Xamarin Forms PCL HttpClient 在 Android 上抛出未处理的异常

c# - 如何制作可滚动的文本框列表?

时间:2019-03-17 标签:c#tooltiphelp

batch-file - 将基于特定大小的日志旋转为日期/时间戳副本

windows - 在 Windows 命令提示符下转义尖括号

c# - 使用 Asp.net Core Web Api 响应 Native

batch-file - 批量叠加 Logo 到视频文件目录

batch-file - Nuget 包并在同一批处理脚本中推送

java - 在 cmd 中用空格启动 jar