Implementing file downloads with Visual C #

Source: Internet
Author: User
Tags file upload function prototype implement resource thread visual studio
visual| download one. Overview:

This article introduces some basic knowledge of Internet communication programming with Visual C # through an example. We know. NET class includes the request/response layer, the Application protocol layer, the Transport layer and so on. In this program, we use the WebRequest class at the request/response level and the WebClient class to achieve a high degree of abstraction in Internet communication services. The function of this program is to complete the downloading of network files.

Two Implementation principle:

The principle of program implementation is relatively simple, mainly used WebClient class and FileStream class. Where the WebClient class is in the System.Net namespace, the primary function of the class is to provide a public method for sending data to the resource identified by the URI and receiving data from the resource identified by the URI. We use the DownloadFile () method to download the network files locally. The file data is then written to the local file using the instance object of the FileStream class as a data stream. This completes the download of the network files.

Three Implementation steps:

First, open Visual Studio.NET and create a new project for a Visual C # Windows application that you might name as "Mygetcar."
Next, lay out the main interface. We first add the following controls to the main form: Two label controls, two text box controls, a button control, and a status bar control. The final main form is shown in the following illustration:



Complete the design of the main form, and we'll finish writing the code.

It is fairly easy to write code on the basis of understanding the fundamentals. The main thing we use in the program is the WebClient class, but before we call the instance object of the WebClient class, we need to emit a request for the Uniform Resource Identifier (URI) with the object of the WebRequest class.

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, and the catch block catches the possible exception and displays the exception information. The urladdress is the requested network host name.

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

public void DownloadFile (string address, string fileName);

Where parameter address is the name of the local file from which the data is downloaded uri,filename the data to be received.
We then use the OpenRead () method to open a readable stream that completes the ability to download data from a resource with the specified URI. The function prototype is as follows:

Ublic Stream OpenRead (string address);
 
where the parameter address ibid.

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

Also, when you use the above method, you will probably need to deal with the following kinds of exceptions:

WebException: An error occurred while downloading the data.

UriFormatException: The URI formed by combining baseaddress, address, and QueryString is invalid.

The code for this section is as follows: (client is WebClient object, declared at the beginning of this class)

Statusbar.text = "Start downloading files ...";
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 completing the reading of the file data, we use the instance object of the FileStream class 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 for the main part of the program is complete, but it will take some work to complete the program. Because when the program receives the network file data to apply to the while loop body, this will very occupy the program resources, the form of performance is the main form is not free to move. In order to solve this problem, we use multithreaded mechanism in the program. We create a new thread in the Response button's event, which is used to implement the network file download function. In this way, the thread and program of the file download coexist, sharing process resources, making the program run smoothly. In this way, we add the following code to the button control's message response function:

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

The implementation function of the thread is Startdownload (), and the code described above is the main part of the function.

Finally, because the program is applied to the WebRequest, WebClient, FileStream, thread and other classes, so 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;
Here is the source code for the program:

Using System;
Using System.Drawing;
Using System.Collections;
Using System.ComponentModel;
Using System.Windows.Forms;
Using System.Data;
Using System.Net;
Using System.IO;
Using System.Threading;

Namespace Mygetcar
{
///
Summary description of the Form1.
///
public class Form1:System.Windows.Forms.Form
{
Private System.Windows.Forms.Label Label1;
Private System.Windows.Forms.Label Label2;
Private System.Windows.Forms.TextBox srcaddress;
Private System.Windows.Forms.TextBox taraddress;
Private System.Windows.Forms.StatusBar StatusBar;
Private System.Windows.Forms.Button Start;

Private WebClient client = new WebClient ();

///
The required designer variable.
///
Private System.ComponentModel.Container components = null;

Public Form1 ()
{
//
Required for Windows Forms Designer support
//
InitializeComponent ();

//
TODO: Add any constructor code after the InitializeComponent call
//
}

///
Clean up all resources that are in use.
///
protected override void Dispose (bool disposing)
{
if (disposing)
{
if (Components!= null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing);
}

#region Windows Form Designer generated code
///
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
///
private void InitializeComponent ()
{
This.label1 = new System.Windows.Forms.Label ();
This.label2 = new System.Windows.Forms.Label ();
this.srcaddress = new System.Windows.Forms.TextBox ();
this.taraddress = new System.Windows.Forms.TextBox ();
This.statusbar = new System.Windows.Forms.StatusBar ();
This. Start = new System.Windows.Forms.Button ();
This. SuspendLayout ();
//
Label1
//
This.label1.Location = new System.Drawing.Point (8, 32);
This.label1.Name = "Label1";
This.label1.Size = new System.Drawing.Size (72, 23);
This.label1.TabIndex = 0;
This.label1.Text = "file address:";
This.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
Label2
//
This.label2.Location = new System.Drawing.Point (8, 72);
This.label2.Name = "Label2";
This.label2.Size = new System.Drawing.Size (72, 23);
This.label2.TabIndex = 1;
This.label2.Text = "Save to:";
This.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
Srcaddress
//
This.srcAddress.Location = new System.Drawing.Point (80, 32);
This.srcAddress.Name = "Srcaddress";
This.srcAddress.Size = new System.Drawing.Size (216, 21);
This.srcAddress.TabIndex = 2;
This.srcAddress.Text = "";
//
Taraddress
//
This.tarAddress.Location = new System.Drawing.Point (80, 72);
This.tarAddress.Name = "Taraddress";
This.tarAddress.Size = new System.Drawing.Size (216, 21);
This.tarAddress.TabIndex = 3;
This.tarAddress.Text = "";
//
StatusBar
//
This.statusBar.Location = new System.Drawing.Point (0, 151);
This.statusBar.Name = "StatusBar";
This.statusBar.Size = new System.Drawing.Size (312, 22);
This.statusBar.TabIndex = 4;
//
Start
//
This. Start.flatstyle = System.Windows.Forms.FlatStyle.Flat;
This. Start.location = new System.Drawing.Point (216, 112);
This. Start.name = "Start";
This. Start.size = new System.Drawing.Size (75, 24);
This. Start.tabindex = 5;
This. Start.text = "Start Download";
This. Start.click + = new System.EventHandler (this. Start_click);
//
Form1
//
This. AutoScaleBaseSize = new System.Drawing.Size (6, 14);
This. ClientSize = new System.Drawing.Size (312, 173);
This. Controls.AddRange (new system.windows.forms.control[] {
This. Start,
This.statusbar,
This.taraddress,
This.srcaddress,
This.label2,
This.label1});
This. MaximizeBox = false;
This. Name = "Form1";
This. Text = "File Downloader";
This. ResumeLayout (FALSE);

}
#endregion

///
The main entry point for the application.
///
[STAThread]
static void Main ()
{
Application.Run (New Form1 ());
}

private void Startdownload ()
{
start.enabled = false;
string URL = Srcaddress.text;
int n = URL. LastIndexOf ('/');
String urladdress = URL. Substring (0,n);
String fileName = URL. Substring (N+1,url. LENGTH-N-1);
string Dir = Taraddress.text;
String Path = dir+ ' \ \ ' +filename;

Try
{
WebRequest myre=webrequest.create (urladdress);
}
catch (WebException exp)
{
MessageBox.Show (exp. Message, "Error");
}

Try
{
Statusbar.text = "Start downloading files ...";
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;
}

FileStream fstr = new FileStream (path,filemode.openorcreate,fileaccess.write);
Fstr. Write (Mbyte,0,startmbyte);
Str. Close ();
Fstr. Close ();

Statusbar.text = "Download complete!" ";
}
catch (WebException exp)
{
MessageBox.Show (exp. Message, "Error");
Statusbar.text = "";
}

Start.enabled = true;
}


private void Start_click (object sender, System.EventArgs e)
{
Thread th = new Thread (new ThreadStart (startdownload));
Th. Start ();
}
}
}


Program completed, run the program diagram as follows:


(When you start downloading files)



(When the file is downloaded)

Four Summarize:

I've shown you how to use Visual C # to download network files in a single instance, and it's easy to find out how to use Visual C # for Internet communication programming. In the above program, we only use some of the WebClient class methods, and the WebClient class not only provides a way to download the network file, but also provides a way to upload files, interested readers may wish to try-to implement a file upload device. At the same time, this program is just a very simple example, the program download a Web page, it is only the content of the main page, can not get the pictures, CSS and other files, so to make a better file downloader needs further improvement of the reader.



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.