[Sample Code] Get file from URL

  • 2893
  • 0
  • 2011-11-08

[Sample Code] Get file from URL

這是一個利用HttpWebRequest.GetResponseStream來取得遠端檔案的Sample Code

藉由WebResponse.GetResponseStream回傳的資料流,轉而寫入檔案

 

 


	
//Set want to get file url
string url ="http://....../xxxxxx.txt";

// Create WebRequest
HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(url);
//Create WebResponse
HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse();

//Check HttpWebResponse Status 
if (httpresponse.StatusCode == HttpStatusCode.OK)
{
    //Get ResponseStream
    using (Stream responsestream = httpresponse.GetResponseStream())
    {
        //Create FileStream
        using (FileStream filestream = new FileStream(filepath, FileMode.Create, FileAccess.Write))
        {
            byte[] buffer = new byte[10240];
            int readbytes;
            //Write to file from ResponseStream
            while ((readbytes = responsestream.Read(buffer, 0, buffer.Length))>0)
            {
                filestream.Write(buffer, 0, readbytes);
            }
        }
    }
}
else
    Response.Write("HttpWebResponse Fail");
    

 

 

 

Ref:

 

HttpWebRequest Class

 

WebResponse Class

 

WebResponse.GetResponseStream Method

 

Stream Class

 

若本文對您有所幫助,歡迎轉貼,但請在加註【轉貼】及來源出處,並在附上本篇的超連結,感恩您的配合囉。

By No.18