One. Overview: This article introduces some of the basic knowledge of Internet communication programming with Visual C # through an example. We know that the .NET class contains a request / response layer, an application protocol layer, a transport layer, etc. In this program, we use the WebRequest class in the request / response layer and the WebClient class, etc. to achieve high abstract degree of Internet communication services. The function of this program is to complete the download of the network file. Two. Realization Principle: The principle of program implementation is relatively simple, mainly used to use the WebClient class and the FileStream class. Where the WebClient class is in the System.Net namespace, the primary function of this class is to provide a public method for transmitting data to the URI identifier and resources from the URI identifier. We use the Downloadfile () method to download the network file to the local. The file data is then written to the local file in a data stream with an instance object of the FILESTREAM class. This completes the download of the network file. three. Implementation Steps: First, open Visual Studio.net, create a new Visual C # Windows application, you may be named "MygetCar". Next, the main interface is arranged. We first add the following controls to the main form: Two tag controls, two text box controls, a button control, and a status bar control. The final main form is as shown below: Complete the design of the main form, we will then complete the code writing. It is quite easy to understand the basic principle based on the basis of the basic principle. The program we mainly uses the WebClient class, but before we call the instance object of the WebClient class, we need to send a request for the Unified Resource Identifier (URI) with the WebRequest class object. Try {WebRequest myre = WebRequest.create (UrLaddress);} catch (webException exp) {messagebox.show (exp .Message, "error");} This is a try-catch statement, TRY block completes to URI requests, Catch The block captures possible exceptions and displays exception information. The URLADDRESS is the requested network hostname. After the request is successful, we can use the DownloadFile () method in the instance object of the WebClient class to implement the file download. Its function prototype is as follows: Public void Downloadfile (String Address, String FileName); where the parameter address is the URI from which the data is downloaded, FILENAME is the name of the local file to receive data. Then we use the OpenRead () method to open a readable stream that completes the functionality of downloading data from the resource with the specified URI. Its function prototype is as follows: Ublic Stream OpenRead (String Address); where the parameter address is the same. Finally, you will have a new StreamReader object to read the data of the file, and use a While cycle to constantly read the data, only to read all the data. In addition, when you use the above methods, you may have to handle the following exceptions: WebException: An error occurred while downloading data.
URIFORMATEXCEPTION: The URI configured by combining baseaddress, address, and queryString is invalid. The code of this part is as follows: (Client is a WebClient object, declaring 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 = "is receiving data ... ";" Allmybyte> 0) {INT m = str.read (mbyte, startmbyte, allmyby; if (m == 0) Break; startmbyte = m; allmybyte- = m;} Complete the reading of file data After we use the FileStream class to write these data to a local file: filestream fstr = new filestream (path, filemode.openorcreate, fstr.write); fstr.write (mbyte, 0, startmbyte); this, program main body The part of the code has been completed, but some work must be required to complete all programs. Since the WHILE cycler is applied when the program receives the network file data, it will take advantage of the program resources, the form of performance is that the main form cannot be moved freely. In order to solve this problem, we have used multi-thread mechanism in the program. We create new threads in the event of the response button, which is used to implement the network file download function. Thus, the file download thread and program main thread are caught, share process resources, so that the program runs smoothly. In this way, we add the following code in the message response function of the button control: Thread THREADSTART (New ThreadStart (StartDownload)); th.Start (); this thread's implementation function is startdownload (), and the code described above It is the main part of this function.
Finally, because the program is used to WebRequest, WebClient, FileStream, Thread and other classes, the most important thing is to add the following name space at the beginning of the program: use system.net; useing system.io; using system.threading; below is the program source: 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 A summary description of MygetCar {/// /// 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 traddress; private system.windows.forms.statusbar statusbar; private system.windows.forms.button start; private webclient client = new WebClient (); //// / / The designer variable. ///Prate system.componentmodel.container components = null; public form1 () {// // Windows Form Designer Support for // InitializationComponent (); // // Todo: Add any construct after INITIALIZECOMPONENT call Function code //} / / / / / Clean all the resources being used. /// protected {if (disponents! = Null) {components.dispose ();}} Base.dispose ();} #region Windows form designer generated code //////////////> Disposing; / /// Designer Support the required method - Do not use the code editor to modify the // / 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 = "Some 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.traddress.Location = new system.drawing.point (80, 72); this.traddress.name = "taraddress"; this. Taraddress.size = new system.drawing.size (216, 21); this.taraddress.tabindex = 3; this.traddress.text = ""; /// statusbar // this.status bar.location =
New system.drawing.point (0, 151); this.statusbar.name = "statusbar"; this.status bar.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 primary 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, url.length-n-1); string dir = traddress.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 = "Receive 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, flyaccess.write; fstr.write (mbyte, 0, startmbyte); str.close (); fstr.close (); statusbar.text = "Download! "} Catch (webException exp) {messagebox.show (exp.Message," error "); statusbar.text =" ";} start.enabled = true;} private void start_click (object sender, system.eventargs e) { Thread THREAD (New ThreadStart (StartDownload); th.start ();}}} The program is completed, the running program is shown below: (When starting the download file) (the file is downloaded) IV. Summary: