Use Visual C # to download files (2)

Source: Internet
Author: User

The following is the source code of 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 of 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 ();

///
/// Required designer variables.
///
Private System. ComponentModel. Container components = null;

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

//
// TODO: add Any constructor code after InitializeComponent calls
//
}

///
/// Clear all resources in use.
///
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region Windows Form Designer generated code
///
/// The designer supports the required methods-do not use the code editor to modify
/// Content 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.tar Address = 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 = "saved :";
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.tar Address. Location = new System. Drawing. Point (80, 72 );
This.tar Address. Name = "tarAddress ";
This.tar Address. Size = new System. Drawing. Size (216, 21 );
This.tar Address. TabIndex = 3;
This.tar Address. 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.tar Address,
This. srcAddress,
This. label2,
This. label1 });
This. MaximizeBox = false;
This. Name = "Form1 ";
This. Text = "file downloader ";
This. ResumeLayout (false );

}
# Endregion

///
/// Main entry point of 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, URLs. 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 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;
}

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 ();
}
}
}

Iv. Summary

The above example shows you how to download network files using Visual C #. It is very convenient to use Visual C # For Internet communication programming.

In the above program, we only use some methods of the WebClient class. The WebClient class not only provides methods for downloading network files, but also provides methods for uploading files, if you are interested, you may try to use it to implement a File Uploader.

At the same time, this program is just a very simple example. After downloading a webpage, the program obtains only the content on the homepage and cannot obtain images, CSS, and other files, therefore, readers need to make further improvements to make a better File Download device.

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.