asp.net (C #) file Download Implementation Code _ Practical Tips

Source: Internet
Author: User
Tags function prototype urlencode
Copy Code code 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) {}
TransmitFile implementation Download
protected void Button1_Click (object sender, EventArgs e)
{
/* Microsoft provides a new method for the response object TransmitFile to solve the problem of Aspnet_wp.exe process recycling when using Response.BinaryWrite to download more than 400mb of files. 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);
}
WriteFile Implementation Download
protected void button2_click (object sender, EventArgs e)
{
/* using System.IO; */
string filename = "Asd.txt";//client saved file name
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-Block Download
protected void Button3_Click (object sender, EventArgs e)
{
string filename = "Aaa.txt";//client saved file name
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;//100k Read the file every time, read only 100K, which can ease 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;//Gets 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 ();
}
}
Streaming mode download
protected void Button4_Click (object sender, EventArgs e)
{
string filename = "Aaa.txt";//client saved file name
String filePath = Server.MapPath ("Download/aaa.txt");//path///download file as character 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"; Notifies 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 ();
}
}

/*
There are 4 common downloads available for reference:
This article introduces some basic knowledge of Internet communication programming with C # through an example. We know. NET class includes the request/response layer, the Application protocol layer, the Transport layer and so on. In this program, we use the WebRequest class at the request/response level and the WebClient class to achieve a high degree of abstraction in Internet communication services. The function of this program is to complete the downloading of network files.
Implementation principle
The principle of program implementation is relatively simple, mainly used WebClient class and FileStream class. Where the WebClient class is in the System.Net namespace, the primary function of the class is to provide a public method for sending data to the resource identified by the URI and receiving data from the resource identified by the URI. We use the DownloadFile () method to download the network files 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 files.
Implementation steps
First, open Visual Studio.NET and create a new project for a visual C#windows application that you might name as "Mygetcar." Next, lay out the main interface. We first add the following controls to the main form: Two label controls, two text box controls, a button control, and a status bar control.
Set the control properties as follows:
Control type Control Name property Type property value main form Form1 Text property file Download Label control Label1 Text Property file Address: TextAlign Property middleright Label2 Text property save to: TextAlign property MiddleRight text Box control srcaddress Text Property (empty) Taraddress Text property (empty) button control Start FlatStyle Property Flat Text property start download status bar control StatusBar text Properties (empty)
Other properties can be default, and the final main form is shown in the following illustration:
Complete the design of the main form, and we'll finish writing the code.
It is fairly easy to write code on the basis of understanding the fundamentals. The main thing we use in the program is the WebClient class, but before we call the instance object of the WebClient class, we need to emit a request for the Uniform Resource Identifier (URI) with the object of the WebRequest class.
Copy Code code 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, and the catch block catches the possible exception and displays the exception information.   The urladdress is the requested network host name. Once 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 parameter address is the name of the local file from which the data is downloaded uri,filename the data to be received. 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: Public Stream OpenRead (string address);   where the parameter address ibid. The last is to create a new StreamReader object to read the data from the file, and use a while loop body to continuously read the data, only to read all the data.
Also, when you use the above method, you will probably need to deal with the following kinds of exceptions:
WebException: An error occurred while downloading the data.
UriFormatException: The URI formed by combining baseaddress, address, and QueryString is invalid.
The code for this section is as follows: (client is WebClient object, declared at the beginning of this class)
Copy Code code as follows:

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 = "receiving data ...";
while (allmybyte>0) {
int m = str. Read (Mbyte,startmbyte,allmybyte);
if (m==0)
Break
Startmbyte+=m;
Allmybyte-=m;
}

After completing the reading of 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);
*/
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.