2

我知道类似的问题在这个网站上泛滥(双关语),但如果不关闭我正在运行的 .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 提示符中输入“echo date: 18.02.2019”,然后保存该值。

4

1 回答 1

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 窗体应用程序正常工作,您需要将 VSProject Properties -> Application -> Output Type从更改Windows ApplicationConsole Application. 或者您可以通过编辑*.csproj文件并替换<OutputType>WinExe</OutputType><OutputType>Exe</OutputType>. 因此,控制台将在所有应用程序运行期间显示,这可能不适合您。老实说,我不知道如何以其他方式制作它。

于 2019-02-18T16:02:58.710 回答