對curl熟悉的同學都知道curl在linux環境下應用得很廣-命令行下載文件。我為什么會記錄它在windows下的應用呢,原因是之前做項目,客戶給我提供了一個url,按正常的思路,我用webclient去downloadFile就可以直接下載,但是我下載下來的是一個網頁,並沒有把里面的pdf文件下載下來。
客戶提供的url放在網頁上是一個彈窗按鈕問你是否保存下載這個pdf文件,具體的圖片我就不貼出來了。我在想是不是我用webclient寫功能不夠強大,無法模擬網頁的下載功能。找了好幾天,經過測試curl可以實現這個功能,curl相當於一個小型的瀏覽器核心。
操作步驟如下:
一、在網上查找curl Windows環境的安裝包,具體自行查找。
二、下載下來把文件解壓在C盤,然后環境變量添加添加此文件夾,如下圖所示,可以ping一下curl ,驗證安裝是否成功,接下來就是用cmd 執行curl相關命令。


三、代碼如下
public static bool GetFileFromCurl(string url) { try { string strInput = "curl " + "\"" + url + "\"" + " --output " + "\"" + Global.pdfname + "\""; Process p = new Process(); //設置要啟動的應用程序 p.StartInfo.FileName = "cmd.exe"; //是否使用操作系統shell啟動 p.StartInfo.UseShellExecute = false; // 接受來自調用程序的輸入信息 p.StartInfo.RedirectStandardInput = true; //輸出信息 p.StartInfo.RedirectStandardOutput = true; // 輸出錯誤 p.StartInfo.RedirectStandardError = true; //不顯示程序窗口 p.StartInfo.CreateNoWindow = true; //啟動程序 p.Start(); //向cmd窗口發送輸入信息 p.StandardInput.WriteLine(strInput + "&exit"); p.StandardInput.AutoFlush = true; //獲取輸出信息 string strOuput = p.StandardOutput.ReadToEnd(); //等待程序執行完退出進程 p.WaitForExit(); p.Close(); return true; } catch (Exception ex) { Log.WriteLog("GetFileFromCurl:異常" + ex.Message); return false; } }
