使用C#程式從網站下載檔案
使用C#程式從網站下載檔案
資料來源: https://blog.darkthread.net/blog/download-file-with-c/
單純下載:
using System; using System.Net; public class CSharpLab { public static void Test() { WebClient wc = new WebClient(); wc.DownloadFile("http://blog.darkthread.net/images/darkthreadbanner.gif", "b:\\darkthread.gif"); } }
有進度下載:
using System; using System.IO; using System.Net; public class CSharpLab { public static void Test() { string url = "http://blog.darkthread.net/images/darkthreadbanner.gif"; HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse(); System.IO.Stream dataStream = httpResponse.GetResponseStream(); byte[] buffer = new byte[8192]; FileStream fs = new FileStream("X:\\TEMP\\Darkthread.gif", FileMode.Create, FileAccess.Write); int size = 0; do { size = dataStream.Read(buffer, 0, buffer.Length); if (size > 0) fs.Write(buffer, 0, size); } while (size > 0); fs.Close(); httpResponse.Close(); Console.WriteLine("Done at " + DateTime.Now.ToString("HH:mm:ss.fff")); } }