Use Visual C # to download files (1)

Source: Internet
Author: User

I. Overview

This article uses an example to introduce some basic knowledge about Internet communication programming using Visual C. We know that the. Net class includes the request/response layer, application protocol layer, transmission layer, and other layers. In this program, we use the WebRequest class and WebClient class at the request/response layer to implement highly abstract Internet communication services. The function of this program is to download network files.

II. Implementation Principle

The principle of program implementation is relatively simple, mainly using the WebClient class and FileStream class. The WebClient class is in the System. Net namespace. The main function of this class is to send data to the resource identified by the URI and receive data from the resource identified by the URI. We use the DownloadFile () method to download the network file to the local device. Then, use the Instance Object of the FileStream class to write the file data to the local file as a data stream. This completes the download of network files.

3. Implementation steps

First, open Visual Studio. Net and create a project for the Visual C # Windows application. You may wish to name it "MyGetCar ".

Next, deploy the main interface. Add the following controls to the main form: two label controls, two text box controls, one button control, and one status bar control. Shows the final main form:

  

After completing the design of the main form, we will then write the code.

It is quite easy to write the code on the basis of understanding the basic principles. We mainly use the WebClient class in the program. However, before calling the Instance Object of the WebClient class, we need to use the WebRequest Class Object To send a request for the Uniform Resource Identifier (URI.

Try
{
WebRequest myre = WebRequest. Create (URLAddress );
}
Catch (WebException exp)
{
MessageBox. Show (exp. Message, "Error ");
}

This is a try-catch statement. The try block completes the request to the URI. The catch Block captures possible exceptions and displays exception information. URLAddress indicates the requested network host name.

After the request is successful, we can use the DownloadFile () method in the instance object of the WebClient class to download the file. The function prototype is as follows:

Public void DownloadFile (string address, string fileName );

Here, the address parameter is the URI from which the data is downloaded, and fileName is the name of the local file to receive the data.

Then we use the OpenRead () method to open a readable stream, which completes the function of downloading data from resources with a specified URI. The function prototype is as follows:

Ublic Stream OpenRead (string address );
 
The address parameter is the same as above.

The last step is to create a StreamReader object to read data from the file, and use a while loop body to continuously read data, only to read all the data.

When using the above methods, you may need to handle the following exceptions:

WebException: An error occurred while downloading data.

UriFormatException: The URI consisting of BaseAddress, address, and QueryString is invalid.


The code for this part is as follows: (the client is a WebClient object and can be declared at the beginning of this class)

StatusBar. Text = "start to download the file ...";
Client. DownloadFile (URLAddress, fileName );
Stream str = client. OpenRead (URLAddress );
StreamReader reader = new StreamReader (str );
Byte [] mbyte = new byte [100000];
Int allmybyte = (int) mbyte. Length;
Int startmbyte = 0;
StatusBar. Text = "receiving data ...";
While (allmybyte> 0)
{
Int m = str. Read (mbyte, startmbyte, allmybyte );
If (m = 0)
Break;

Startmbyte + = m;
Allmybyte-= m;
}

After reading the file data, we use the FileStream instance object to write the data to the local file:

FileStream fstr = new FileStream (Path, FileMode. OpenOrCreate, FileAccess. Write );
Fstr. Write (mbyte, 0, startmbyte );

In this way, the code of the main part of the program has been completed, but some work is required to complete all the programs. Because the while LOOP body is used when the program receives network file data, it occupies a lot of program resources, in the form that the main form cannot be moved freely. To solve this problem, we use the multithreading mechanism in the program. We create a new thread in the response button event, which is used to download network files. In this way, the file download thread and the main program thread coexist and share process resources, making the program run smoothly. In this way, the following code is added to the Message response function of the button control:

Thread th = new Thread (new ThreadStart (StartDownload ));
Th. Start ();

The implementation function of this thread is StartDownload (), and the Code described above is the main part of this function.

Finally, because WebRequest, WebClient, FileStream, Thread, and other classes are used in the program, the most important thing is to add the following namespace at the beginning of the program:

Using System. Net;
Using System. IO;
Using System. Threading;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.