簡體   English   中英

c# OutputDataReceived 不適用於 curl

[英]c# OutputDataReceived does not work with curl

以下是使用 OutputDataReceived 從 curl 捕獲詳細信息的代碼。

沒有任何信息可以通過這種方式捕獲。 怎么了?

var command = "curl.exe -vs -o test.html https:\\www.google.com";
var procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
var proc = new Process();
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += (s, e) => {if(!string.IsNullOrEmpty(e.Data)) textBoxLog.AppendText(e.Data); };
proc.StartInfo = procStartInfo;
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
proc.Close();

--output(或 -o)將下載的內容寫入給定文件(而不是將其寫入標准輸出)。 cURL 的 output 的 rest(進度表、錯誤消息、詳細模式等)仍然寫入 stderr,顯示在終端中。 https://en.wikipedia.org/wiki/Standard_streams

This means that you can only see the output of the HTML in C# with OutputDataReceived but not the output made by the verbose mode.

正在運行的控制台應用程序中的此代碼將所有詳細信息打印到控制台,而無需使用Console.WriteLine()手動寫入:

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = @"C:\Windows\System32\curl.exe";
startInfo.Arguments = @"https://vi.stackexchange.com/ -vs";
startInfo.RedirectStandardOutput = true;
process.StartInfo = startInfo;
process.Start();

您可以通過蝙蝠的幫助將詳細模式的 output 保存到帶有curltxt 文件中:

curl https://vi.stackexchange.com/ -vs >curl-output.txt 2>&1

或者您可以閱讀帶有ErrorDataReceivedStandardError stream 。

我建議使用HttpWebRequest ,如this question所示,而不是使用 curl 將請求作為Process ,除非您有特定原因。

感謝惡意軟件狼人為我指明了正確的方向。 詳細信息是標准錯誤,而不是標准輸出。 以下是用於捕獲詳細信息的更正代碼。

var command = "curl.exe -vs -o test.html https:\\www.google.com";
var procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
var proc = new Process();
proc.EnableRaisingEvents = true;
proc.ErrorDataReceived += (s, e) => {if(!string.IsNullOrEmpty(e.Data)) textBoxLog.AppendText(e.Data); };
proc.StartInfo = procStartInfo;
proc.Start();
proc.BeginErrorReadLine();
proc.WaitForExit();
proc.Close();

暫無
暫無

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

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