簡體   English   中英

打開命令行並讀取輸出而不關閉

[英]Opening a command line and reading outputs without closing

我知道這個網站上充斥着類似的問題(雙關語),但如果不關閉我正在運行的 .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”go 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 from Windows Application to Console Application進行更改。 或者您可以通過編輯*.csproj文件並將<OutputType>WinExe</OutputType>替換為<OutputType>Exe</OutputType> 因此,控制台將在所有應用程序運行時顯示,這可能是您不希望看到的。 老實說,我不知道如何以其他方式實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM