Use C # Builder to download files

Source: Internet
Author: User
Author: Xu Changyou

I. Overview:
This article uses an example to introduce some basic knowledge about Internet communication programming using C # builder. 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 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 downfile () method to download the object 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. In this way, the file is downloaded.
3. Implementation steps:
1. First, open C # builder, file-> New-> C # application. Here we set name to "Download ".
2. settings of the main interface. Set text to "File Download", startposition to centerscreen, and maximizebox to false. we add the following controls on the main form: two label controls label1, label2, textbox1, button1, and progressbar1.
Label1: text is URL; label2: text is the download progress; textbox1: text is set to NULL; button1: text is set to download;
3. Program Encoding
// Process downfile, used to download the object
Private void downfile ()
{
String filename;
WebClient downfile = new WebClient ();
Long fbytes;
If (textBox1.Text! = "")
{
SaveFileDialog1.ShowDialog ();
FileName = saveFileDialog1.FileName;
If (FileName! = "")
{
// Obtain the file size
WebRequest wr_request = WebRequest. Create (textBox1.Text );
WebResponse wr_response = wr_request.GetResponse ();
Fbytes = wr_response.ContentLength;
ProgressBar1.Maximum = (int) fbytes;
ProgressBar1.Step = 1;
Wr_response.Close ();
// Start data download
DownFile. DownloadData (textBox1.Text );
Stream strm = DownFile. OpenRead (textBox1.Text );
StreamReader reader = new StreamReader (strm );
Byte [] mbyte = new byte [fbytes];
Int allmybyte = (int) mbyte. Length;
Int startmbyte = 0;
While (fbytes> 0)
{
Int m = strm. Read (mbyte, startmbyte, allmybyte );
If (m = 0) break;
Startmbyte + = m;
Allmybyte-= m;
ProgressBar1.value + = m;
}
FileStream fstrm = new FileStream (FileName, FileMode. OpenOrCreate, FileAccess. Write );
Fstrm. Write (mbyte, 0, startmbyte );
Strm. Close ();
Fstrm. Close ();
ProgressBar1.value = progressBar1.Maximum;
}
} Else
{
MessageBox. Show ("no file to download! ");
}
}

// Double-click the Download button and enter the following code:
Thread th = new thread (New threadstart (downfile ));
Th. Start ();

// The complete code is as follows:
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 download
{
/// <Summary>
/// Summary description for WinForm.
/// </Summary>
Public class WinForm: System. Windows. Forms. Form
{
/// <Summary>
/// Required designer variable.
/// </Summary>
Private System. ComponentModel. Container components = null;
Private System. Windows. Forms. Label label1;
Private System. Windows. Forms. TextBox textBox1;
Private System. Windows. Forms. Button button1;
Private System. Windows. Forms. SaveFileDialog saveFileDialog1;
Private System. Windows. Forms. Label label2;
Private System. Windows. Forms. ProgressBar progressBar1;

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

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

/// <Summary>
/// Clean up any resources being used.
/// </Summary>
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region Windows Form Designer generated code
/// <Summary>
/// Required method for Designer support-do not modify
/// The contents of this method with the code editor.
/// </Summary>
Private void InitializeComponent ()
{
This. label1 = new System. Windows. Forms. Label ();
This. textBox1 = new System. Windows. Forms. TextBox ();
This. button1 = new System. Windows. Forms. Button ();
This. saveFileDialog1 = new System. Windows. Forms. SaveFileDialog ();
This. label2 = new System. Windows. Forms. Label ();
This. progressBar1 = new System. Windows. Forms. ProgressBar ();
This. SuspendLayout ();
//
// Label1
//
This. label1.Location = new System. Drawing. Point (40, 40 );
This. label1.Name = "label1 ";
This. label1.Size = new System. Drawing. Size (40, 16 );
This. label1.TabIndex = 0;
This. label1.Text = "URL :";
//
// TextBox1
//
This. textBox1.Location = new System. Drawing. Point (72, 36 );
This. textBox1.Name = "textBox1 ";
This. textBox1.Size = new System. Drawing. Size (256, 21 );
This. textBox1.TabIndex = 1;
This. textBox1.Text = "";
//
// Button1
//
This. button1.location = new system. Drawing. Point (256,120 );
This. button1.name = "button1 ";
This. button1.tabindex = 2;
This. button1.text = "Download ";
This. button1.click + = new system. eventhandler (this. button#click );
//
// Label2
//
This. label2.location = new system. Drawing. Point (8, 80 );
This. label2.name = "label2 ";
This. label2.size = new system. Drawing. Size (72, 23 );
This. label2.tabindex = 3;
This. label2.Text = "download progress :";
//
// ProgressBar1
//
This. progressBar1.Location = new System. Drawing. Point (72, 80 );
This. progressBar1.Name = "progressBar1 ";
This. progressBar1.Size = new System. Drawing. Size (256, 16 );
This. progressBar1.TabIndex = 4;
//
// WinForm
//
This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );
This. ClientSize = new System. Drawing. Size (360,173 );
This. Controls. Add (this. progressBar1 );
This. Controls. Add (this. label2 );
This. Controls. Add (this. button1 );
This. Controls. Add (this. textBox1 );
This. Controls. Add (this. label1 );
This. MaximizeBox = false;
This. Name = "WinForm ";
This. StartPosition = System. Windows. Forms. FormStartPosition. CenterScreen;
This. Text = "File Download ";
This. ResumeLayout (false );
}
# Endregion

/// <Summary>
/// The main entry point for the application.
/// </Summary>
[STAThread]
Static void Main ()
{
Application. Run (new WinForm ());
}

Private void downfile ()
{
String FileName;
WebClient DownFile = new WebClient ();
Long fbytes;
If (textBox1.Text! = "")
{
SaveFileDialog1.ShowDialog ();
FileName = saveFileDialog1.FileName;
If (FileName! = "")
{
// Obtain the file size
WebRequest wr_request = WebRequest. Create (textBox1.Text );
WebResponse wr_response = wr_request.GetResponse ();
Fbytes = wr_response.ContentLength;
ProgressBar1.Maximum = (int) fbytes;
ProgressBar1.Step = 1;
Wr_response.Close ();
// Start data download
DownFile. DownloadData (textBox1.Text );
Stream strm = DownFile. OpenRead (textBox1.Text );
StreamReader reader = new StreamReader (strm );
Byte [] mbyte = new byte [fbytes];
Int allmybyte = (int) mbyte. Length;
Int startmbyte = 0;
While (fbytes> 0)
{
Int m = strm. Read (mbyte, startmbyte, allmybyte );
If (m = 0) break;
Startmbyte + = m;
Allmybyte-= m;
ProgressBar1.value + = m;
}
FileStream fstrm = new FileStream (FileName, FileMode. OpenOrCreate, FileAccess. Write );
Fstrm. Write (mbyte, 0, startmbyte );
Strm. Close ();
Fstrm. Close ();
ProgressBar1.value = progressBar1.Maximum;
}
} Else
{
MessageBox. Show ("no file to download! ");
}
}
Private void button#click (object sender, System. EventArgs e)
{
Thread th = new Thread (new ThreadStart (downfile ));
Th. Start ();
}
}
}

4. Press F9 to run the program. Enter 1 and click "Download.


Iv. Conclusion:
The preceding simple example shows how to download files using C # builder. It is very convenient to use C # builder for Internet communication programming. In the above program, we only use some methods of the WebClient class, while the WebClient class not only provides the file download method, but also provides methods such as file upload, if you are interested, try it yourself and check the help.
Multiple Threads are used in the program. This is because the resources occupied by the WebClient class are too large. downloading files will make the display of the entire window incomplete. Without multithreading, you cannot move windows or perform other operations when downloading files.
Interested friends can go to my home page to download source code http://yousoft.hi.com.cn

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.