상세 컨텐츠

본문 제목

WebClient Download Sample

C#

by 탑~! 2011. 11. 17. 10:05

본문

// Specify the URL of the file to download
const string url = @"http://www.datavoila.com/download/datavoila-setup.exe";

// Specify the path of the file to write to
const string outputFile = @"C:\Downloads\datavoila-setup.exe";

// Create output directory (if necessary)
string outputFolder = Path.GetDirectoryName(outputFile);
if (!Directory.Exists(outputFolder))
    Directory.CreateDirectory(outputFolder);

WebClient webClient =
new WebClient();

// Optional: Specify proxy server settings
//webClient.Proxy = new WebProxy("http://proxyserver:80/", true);
//webClient.Proxy.Credentials = new NetworkCredential("user", "password");

// Optional: Add "User-Agent" header
//webClient.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)";

// Download the file and write it to disk
using (Stream webStream = webClient.OpenRead(url))
using (FileStream fileStream = new FileStream(outputFile, FileMode.Create))
{
   
var buffer = new byte[32768];
   
int bytesRead;
    Int64 bytesReadComplete =
0// Use Int64 for files larger than 2 gb
   
   
// Get the size of the file to download
    Int64 bytesTotal = Convert.ToInt64(webClient.ResponseHeaders[
"Content-Length"]);
   
   
// Start a new StartWatch for measuring download time
    Stopwatch sw = Stopwatch.StartNew();
   
   
// Download file in chunks
   
while ((bytesRead = webStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        bytesReadComplete += bytesRead;
        fileStream.Write(buffer,
0, bytesRead);
       
       
// Output current progress to the "Output" editor
        StringBuilder sb =
new StringBuilder();
        sb.AppendLine(String.Format(
"Progress: {0:0%}", (double)bytesReadComplete / bytesTotal));
        sb.AppendLine(String.Format(
"Downloaded: {0:0,0} Bytes", bytesReadComplete));
        sb.AppendLine(String.Format(
"Time Elapsed: {0:0,.00}s", sw.ElapsedMilliseconds));
        sb.AppendLine(String.Format(
"Average Speed: {0:0,0} KB/s", sw.ElapsedMilliseconds > 0 ? bytesReadComplete / sw.ElapsedMilliseconds / 1.024 : 0));
        Output.Text = sb.ToString();
    }
   
    sw.Stop();
}


출처 : http://www.datavoila.com/projects/internet/download-file-using-webclient-class.html

'C#' 카테고리의 다른 글

File Transaction  (0) 2011.11.17
EscapeSequence  (0) 2011.11.17
c# 시간 측정 방법  (0) 2011.11.04
강제 형 변환(cast)보다는 as, is 연산자를 사용하는 것이 좋다  (0) 2011.10.24
SqlBulkCopy  (0) 2011.10.22

관련글 더보기