以下是使用 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();
uj5u.com熱心網友回復:
--output(或 -o)將下載的內容寫入給定檔案(而不是將其寫入標準輸出)。cURL 的其余輸出(進度表、錯誤訊息、詳細模式等)仍然寫入 stderr,顯示在終端中。https://en.wikipedia.org/wiki/Standard_streams
這意味著您只能看到 C# 中的 HTML 的輸出,OutputDataReceived但不能看到詳細模式的輸出。
此代碼在正在運行的控制臺應用程式中,將所有詳細資訊列印到控制臺,而無需手動撰寫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();
您可以通過這種方式在bat的幫助下將詳細模式的輸出保存到帶有curl的txt 檔案中:
curl https://vi.stackexchange.com/ -vs >curl-output.txt 2>&1
或者您可以使用ErrorDataReceived讀取StandardError 流。
除非您有特定原因,否則我建議使用此問題中顯示的HttpWebRequest而不是使用 curl 將請求作為Process。
uj5u.com熱心網友回復:
感謝惡意軟體狼人為我指明了正確的方向。詳細資訊是標準錯誤,而不是標準輸出。以下是用于捕獲詳細資訊的更正代碼。
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/407765.html
標籤:
