close
這個是JK改寫的 使用 WebClient 的網路URL下載動作
參考自: http://blog.darkthread.net/blogs/darkthreadtw/archive/2008/11/26/3660.aspx#3860



Protected Sub Button4_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button4.Click


Dim rootPath = HttpContext.Current.Request.MapPath("~/") '取得當前目錄PATH
Dim url = "http://l.yimg.com/f/i/tw/hp/mh/09purple.gif" '欲下載圖的連結URL
Dim client As New WebClient()
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
' Add a user agent header in case the requested URI contains a query.


'-----------------------

'寫法1(簡易): '下載回來放的位置是一個指定的位置 (這是一般客戶端的下載動作)
' client.DownloadFile(url, "c:/aaa.gif") 'JK:要給它放置下載回來的檔案的絕對路徑名稱

'-------------------------------

'寫法2(仔細): '下載回來的位置會是網站的根目錄內(也就是伺服器端的主目錄,這作法是SERVER去下載URL的意思)
Dim floderPath = "download/setfilename.gif"
Dim savePath = rootPath & floderPath
client.DownloadFile(url, savePath) '要給它放置下載回來的檔案的絕對路徑名稱
MsgBox("OK" + savePath)

'---------------------------------------

End Sub



//================================

進階
webClient 是以下http Request 和 Response 的組成
參考自: http://blog.darkthread.net/blogs/darkthreadtw/archive/2008/11/26/3660.aspx#3860

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"));
    }
}
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 prague12 的頭像
    prague12

    prague12

    prague12 發表在 痞客邦 留言(1) 人氣()