Implementation Code of asp.net (c #) File Download

Source: Internet
Author: User

Copy codeThe Code is as follows:
Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. IO;
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e ){}
// Download TransmitFile
Protected void button#click (object sender, EventArgs e)
{
/* Microsoft provides a new method for the Response object, TransmitFile, to solve the problem that the aspnet_wp.exe process cannot be downloaded when the Response. BinaryWrite file is downloaded over Mbit/s. The Code is as follows :*/
Response. ContentType = "application/x-zip-compressed"; Response. AddHeader ("Content-Disposition", "attachment?filename=z.zip ");
String filename = Server. MapPath ("DownLoad/z.zip"); Response. TransmitFile (filename );
}
// Download WriteFile
Protected void Button2_Click (object sender, EventArgs e)
{
/* Using System. IO ;*/
String fileName = "asd.txt"; // file name saved by the client
String filePath = Server. MapPath ("DownLoad/aaa.txt"); // path
FileInfo fileInfo = new FileInfo (filePath );
Response. Clear ();
Response. ClearContent ();
Response. ClearHeaders ();
Response. AddHeader ("Content-Disposition", "attachment; filename =" + fileName); Response. AddHeader ("Content-Length", fileInfo. Length. ToString ());
Response. AddHeader ("Content-Transfer-Encoding", "binary ");
Response. ContentType = "application/octet-stream ";
Response. ContentEncoding = System. Text. Encoding. GetEncoding ("gb2312 ");
Response. WriteFile (fileInfo. FullName );
Response. Flush ();
Response. End ();
}
// WriteFile multipart download
Protected void Button3_Click (object sender, EventArgs e)
{
String fileName = "aaa.txt"; // file name saved by the client
String filePath = Server. MapPath ("DownLoad/aaa.txt"); // path
System. IO. FileInfo fileInfo = new System. IO. FileInfo (filePath );
If (fileInfo. Exists = true)
{
Const long ChunkSize = 102400; // 100 K reads only 100 K each time, which can relieve the pressure on the server
Byte [] buffer = new byte [ChunkSize];
Response. Clear ();
System. IO. FileStream iStream = System. IO. File. OpenRead (filePath );
Long dataLengthToRead = iStream. Length; // obtain the total size of the downloaded file
Response. ContentType = "application/octet-stream ";
Response. AddHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. UrlEncode (fileName); while (dataLengthToRead> 0 & Response. IsClientConnected)
{
Int lengthRead = iStream. Read (buffer, 0, Convert. ToInt32 (ChunkSize); // Read size Response. OutputStream. Write (buffer, 0, lengthRead );
Response. Flush ();
DataLengthToRead = dataLengthToRead-lengthRead;
}
Response. Close ();
}
}
// Stream download
Protected void Button4_Click (object sender, EventArgs e)
{
String fileName = "aaa.txt"; // file name saved by the client
String filePath = Server. MapPath ("DownLoad/aaa.txt"); // path // DownLoad the file as a response stream
FileStream fs = new FileStream (filePath, FileMode. Open );
Byte [] bytes = new byte [(int) fs. Length]; fs. Read (bytes, 0, bytes. Length );
Fs. Close ();
Response. contentType = "application/octet-stream"; // notify the browser to download the file instead of opening Response. addHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. urlEncode (fileName, System. text. encoding. UTF8 ));
Response. BinaryWrite (bytes );
Response. Flush ();
Response. End ();
}
}

/*
Four download methods are provided for reference:
This article uses an example to introduce some basic knowledge of using C # For Internet communication programming. 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 network files.
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 DownloadFile () method to download the network file 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. This completes the download of network files.
Steps
First, open Visual Studio. Net and create a project for the Visual C # Windows application. You may wish to name it "MyGetCar ". Next, deploy the main interface. Add the following controls to the main form: two label controls, two text box controls, one button control, and one status bar control.
Set the properties of each control as follows:
Control Type Control Name property type property value main form Form1 Text property file downloader label control Label1 Text property file address: TextAlign properties MiddleRight Label2 Text property saved to another: textAlign attribute MiddleRight Text box control srcAddress Text attribute (null) tarAddress Text attribute (null) button control Start FlatStyle attribute Flat Text attribute Start Download Status Bar control StatusBar Text attribute (null)
Other attributes can be default values. The final main form is shown in:
After completing the design of the main form, we will then write the code.
It is quite easy to write the code on the basis of understanding the basic principles. We mainly use the WebClient class in the program. However, before calling the Instance Object of the WebClient class, we need to use the WebRequest Class Object To send a request for the Uniform Resource Identifier (URI.
Copy codeThe Code is as follows:
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. The catch Block captures possible exceptions and displays exception information. URLAddress indicates the requested network host name. After the request is successful, we can use the DownloadFile () method in the instance object of the WebClient class to download the file. The function prototype is as follows: public void DownloadFile (string address, string fileName). The parameter address is the URI from which data is downloaded, and fileName is the name of the local file to receive data. Then we use the OpenRead () method to open a readable stream, which completes the function of downloading data from resources with a specified URI. The function prototype is as follows: public Stream OpenRead (string address). The parameter address is the same as above. The last step is to create a StreamReader object to read data from the file, and use a while loop body to continuously read data, only to read all the data.
When using the above methods, you may need to handle the following exceptions:
● WebException: An error occurred while downloading data.
● UriFormatException: The URI consisting of BaseAddress, address, and QueryString is invalid.
The code for this part is as follows: (the client is a WebClient object and can be declared at the beginning of this class)
Copy codeThe Code is as follows:
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;
}

After reading the file data, we use the FileStream instance object to write the data to the local file:
FileStream fstr = new FileStream (Path, FileMode. OpenOrCreate, FileAccess. Write); fstr. Write (mbyte, 0, startmbyte );
*/

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.