Download data over HTTP or FTP

Problem: You need a quick, simple way to download data from the internet using HTTP or FTP.

Solution: You can use the methods of the System.Net.WebClient class. 

Code: It’s very easy!!. The .NET Framework provides several mechanisms for transferring data over the Internet. One of the easier approaches is to use the System.Net.WebClass class. WebClient provides many high-level methods that simplify the transfer of data by specifying the source as a uniform resourse identifier (URI). The URI can specify that a file(file://), FTP (ftp://), or HTTP (http:// or https://) scheme be used to download the resource.

Technorati のタグ:

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace DataDownload
{
    class Program
    {
        private static void Main()
        {
            string uri = "http://www.microsoft.com/japan/";

            // make a client
            WebClient client = new WebClient();

            // get the contents of the file
            Console.WriteLine("Downloading {0} " + uri);
            // download the page and store the bytes
            byte[] bytes;
            try
            {
                bytes = client.DownloadData(uri);
            }
            catch (WebException we)
            {
                Console.WriteLine(we.ToString());
                return;
            }
            // Write the HTML out
            string page = Encoding.ASCII.GetString(bytes);
            Console.WriteLine(page);

            // go get the file
            Console.WriteLine("Retrieving file from {0}…\r\n", uri);
            // get file and put it in a temp file
            string tempFile = Path.GetTempFileName();
            try
            {
                client.DownloadFile(uri, tempFile);
            }
            catch (WebException we)
            {
                Console.WriteLine(we.ToString());
                return;
            }
            Console.WriteLine("Downloaded {0} to {1}", uri, tempFile);

            uri = "ftp://ftp.microsoft.com/ResKit/win2000/whoami.zip";
            WebClient client2 = new WebClient();

            Console.WriteLine("Downloading {0} " + uri);
            try
            {
                client2.DownloadFile(uri, "whoami.zip");
            }
            catch (WebException we)
            {
                Console.WriteLine(we.ToString());
                return;
            }
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s