2013年5月27日 星期一

[C#] Download files from website.

We have two ways to download files from website by using .net framework.

1. WebClient.
using System.Net;

private void button1_Click(object sender, EventArgs e)
{
    WebClient wc = new WebClient();
    wc.DownloadFile("http://www.taifex.com.tw/DailyDownload/Daily_2013_05_24.zip", "d:\\Daily_2013_05_24.zip");
}


2. HttpRequest + Stream
using System.IO;
using System.Net;

private void button1_Click(object sender, EventArgs e)
{
    string url = "http://www.taifex.com.tw/DailyDownload/Daily_2013_05_24.zip";
    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("d:\\Daily_2013_05_24.zip", 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"));
}



Reference:
http://blog.darkthread.net/post-2008-10-14-download-file-with-c.aspx

沒有留言:

張貼留言