Geeks With Blogs
Pranav`s TechNiche technical thoughts of a coffee addicted developer
         The System.Net namespace contain most of the .NET base class that deal with networking from perspective of the client. The System.Net namespace is generally concerned with Higher-level operations for example download and upload files and making requests using the HTTP and other protocols.

The WebClient Class

If you want to do is carry out a fairly simple operation such as requesting a file from a particular URL, Then you will probably find easiest .NET class to use is System.Net.WebClient. This class is extremely high-level class Designed to perform basic operations with only one or two commands

Downloading Files

         There are two ways of downloading a file from a web site using WebClient, depending on whether we want to save the file, or process the contents of the directly within your application. If we simply want to save the file then we should call the DownloadFile() method takes two parameters, The URL from where we want to retrieve the file, and the file name ( or path) that we want to save the file to.

WebClient Client = new WebClient ();
Client.DownloadFile("", " index.aspx");

More commonly, your application will want to process the data retrieved from the web site. In order to do this, you use the OpenRead () method, Which returns a stream reference. You can then simply retrieve the data from the stream.

WebClient Client = new WebClient ();
Stream strm = Client.OpenRead ("");

The following code will demonstrate the WebClient.OpenRead () method.

In this case we will simply display the contents of the downloaded data in list box.

We create the project as standard Windows C# application, and a list box called listbox1, in which we will display the contents of the downloaded file. We make the following changes to the constructor of the main form.

public form1()

    System.Net.WebClient theClient = new WebClient();
    Stream objStrm = theClient.OpenRead("");
    StreamReader sr = new StreamReader(objStrm);
    string line;
        line = sr.ReadLine();
    while (line !=null);

Uploading Files

         The webClient class also features UploadFile() and UploadData() methods. The difference between them is that UploadFile() uploads a specified file given the file name, While UploadData() uploads binary data, which is supplied as an array of bytes:

WebClient  theClient = new WebClient();

byte [] image;

//code to initialize image so it contains all the binary data for some jpg file
client.UploadData("", image);
Posted on Monday, October 26, 2009 12:33 PM .NET | Back to top

Comments on this post: Uploading and Downloading files to a website using C#

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Pranav | Powered by: