C upload files to the server (including the source of the receiving end)

Source: Internet
Author: User
Tags function prototype

This article demo:http://www.wisdomdd.cn/wisdom/resource/articledetail.htm?resourceid=1067

Examples show you how to download network files in Visual C #, and it is convenient to use Visual C # for Internet communication programming. In the above program, we only used some methods of the WebClient class, and the WebClient class not only provides the method of downloading the network file, but also provides the method of file uploading.

"Introduction to Instances"

A Overview:

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

Two Implementation principle:

The principle of program implementation is relatively simple, mainly used in 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 sending data to and receiving data from the resource identified by the URI. We use the DownloadFile () method to download the network file 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 file.

Three Implementation steps:

First, open Visual Studio.NET and create a new project for a Visual C # Windows application that you might name "Mygetcar".

Next, decorate the main interface. Let's 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 looks like this:

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

It is fairly easy to write code based on understanding the fundamentals. Our main use in the program is the WebClient class, but before we call the instance object of the WebClient class, we need to make a request to 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.

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

public void DownloadFile (string address, string fileName);

Where the parameter address is the name of the local file to receive data from the Uri,filename to which the data is being downloaded.

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. Its function prototype is as follows:

Ublic Stream OpenRead (string address);

where the parameter address ibid.

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

Also, when using the above method, you will probably need to handle the following kinds of exceptions:

WebException: An error occurred while downloading data.

UriFormatException: The URI that is composed of baseaddress, address, and QueryString is not valid.

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

Statusbar.text = "Start download 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 we have finished reading 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 some work is required to complete the program. Because when the program receives the network file data, it applies to the while loop body, which takes up the program resources, and the form of the main form is not free to move. In order to solve this problem, we used the multithreading mechanism in the program. We create a new thread in the event of the response button, which is used to implement the network file download function. As a result, the threads and programs of the file download coexist, sharing process resources and 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 this thread is Startdownload (), and the code described above is the body part of the function.

Finally, because the program is applied to WebRequest, WebClient, FileStream, thread and other classes, the most important thing is to add the following namespaces at the beginning of the program:

Using System.Net;

Using System.IO;

Using System.Threading;

Here is the program source code

Using system;using system.drawing;using system.collections;using system.componentmodel;using System.Windows.Forms; A summary description of the using system.data;using system.net;using system.io;using system.threading;namespace 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 taraddress;private System.Windows.Forms.StatusBar statusbar;private System.Windows.Forms.Button start;private WebClient client = new WebClient (),//////required designer variable. Private System.ComponentModel.Container components = Null;public Form1 () {////Windows Forms Designer support required// InitializeComponent ();////TODO: Add any constructor code after the InitializeComponent call//}//////clean up all the resources that are in use. protected override void Dispose (bool disposing) {if (disposing) {if (%! = NULL) {components. Dispose ();}} Base. Dispose (disposing);} #region The Windows Form Designer generated code//////designer supports the requiredMethod-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 (); Start = new System.Windows.Forms.Button (); SuspendLayout ();////label1//this.label1.location = new System.Drawing.Point (8, +); this.label1.Name = "Label1"; This.label1.Size = new System.Drawing.Size, 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, 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 ( (thi);S.srcaddress.name = "Srcaddress"; this.srcAddress.Size = new System.Drawing.Size (216); 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, +); 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, n); this.statusBar.TabIndex = 4;/ Start//this. Start.flatstyle = System.windows.forms.flatstyle.flat;this. Start.location = new System.Drawing.Point (216, (); Start.name = "Start"; Start.size = new System.Drawing.Size (in.); Start.tabindex = 5;this. Start.text = "Start Download"; Start.click = new System.EventHandler (this. Start_click);////form1//this. AutoScaleBaseSize = new System.Drawing.Size (6, +); ClientSize = new System.Drawing.Size (312, 173); COntrols. AddRange (New system.windows.forms.control[] {this. Start,this.statusbar,this.taraddress,this.srcaddress,this.label2,this.label1}); MaximizeBox = False;this. Name = "Form1"; Text = "File Downloader"; ResumeLayout (false);} #endregion The 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,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 download 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 = Newfilestream (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 ();}}}

  

The program is complete,

Four Summarize:

I've shown you how to use Visual C # to download network files in one instance, and it's easy to see that programming for Internet Communication in Visual C # is convenient. In the above program, we only used some methods of WebClient class, and WebClient class not only provides the method of downloading network files, but also provides the method of uploading files, interested readers may wish to try-to implement a file uploader. At the same time this program is just a very simple example, the program downloaded a Web page, it is only the content of the main page, do not get the image, CSS and other files, so to make a better file downloader also need to further improve the reader.

Instance

"Core Code"

<summary>///webclient upload file to server///</summary>///<param name= "Filenamepath" > file name, full path format </ param>///<param name= "uristring" > server folder path </param>private void UploadFile (String filenamepath,string uristring) {//string fileName = filenamepath.substring (Filenamepath.lastindexof ("//") 1); NewFileName = DateTime.Now.ToString ("Yymmddhhmmss") DateTime.Now.Millisecond.ToString () filenamepath.substring ( Filenamepath.lastindexof (".")); String filenameext = Filename.substring (Filename.lastindexof (".") 1); if (Uristring.endswith ("/") = = false) uristring = Uristring "/"; uristring = uristring newfilename;/**////Create WebClient instance WebClient mywebclient = new WebClient (); Mywebclient.credentials = credentialcache.defaultcredentials;//The file to be uploaded FileStream fs = new FileStream (Filenamepath, FileMode.Open, FileAccess.Read);//filestream fs = OpenFile (); BinaryReader r = new BinaryReader (FS) try{//using the UploadFile method can be//mywebclient.uploadfile in the following format (uristring, "PUT", Filenamepath); byte[] Postarray =R.readbytes ((int) fs. Length); Stream Poststream = Mywebclient.openwrite (uristring, "PUT"), if (poststream.canwrite) {poststream.write (postArray,0, Postarray.length);} Else{messagebox.show ("The file is not currently writable! ");} Poststream.close ();} Catch{messagebox.show ("File upload failed, please retry ~");}} /**////<summary>///Download server file to client///</summary>///<param name= "URL" > downloaded file address, absolute path </param>// /<param name= "Dir" > Other directory </param>public void Download (String url,string Dir) {WebClient client = new WebClient (); string fileName = URL. Substring (URL. LastIndexOf ("//") 1); The file name that was downloaded is string Path = Dir filename; Save as absolute path + filename try{webrequest myre=webrequest.create (URL);} Catch{//messagebox.show (exp. Message, "Error");} Try{client. DownloadFile (Url,path);} Catch{//messagebox.show (exp. Message, "Error");}}

  

C upload files to the server (including the source of the receiving end)

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.