C # Several ways to implement file downloads

Source: Internet
Author: User
Tags urlencode

The previous blog also said that the next C # in the export of Excel through XML, these file operations are very useful, the following is the download of the file, before the project is to write it in the space log, there is time to get them all out

Let's put the code in question.

Using system;using system.data;using system.configuration;using system.collections;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;namespace infoplatclient.netdisk{public partial class download:com. Drpeng.  Common.WebStruct.BaseForm {//<summary>///Get the path to download the file///</summary> Private String Filerpath {get {return request["filerpath"] = = null?            "": request["Filerpath"]; }}///<summary>//Get the name of the file to download///</summary> protected void Page_ Load (object sender, EventArgs e) {if (! IsPostBack) this.        DownloadFile ();                } public void DownloadFile () {response.clearheaders ();                Response.Clear (); Response.expIres = 0;                Response.Buffer =true;                Response.AddHeader ("Accept-language", "ZH-TW");                String name = System.IO.Path.GetFileName (Filerpath);                System.IO.FileStream files = new FileStream (Filerpath, FileMode.Open, FileAccess.Read, FileShare.Read);                Byte[] Bytefile=null; if (Files.                Length = = 0) {bytefile=new byte[1]; } else {bytefile = new byte[files.                Length]; } files.                Read (bytefile, 0, (int) bytefile.length); Files.                             Close (); Response.AddHeader ("Content-disposition", "attachment;filename=" + httputility.urlencode (name,                SYSTEM.TEXT.ENCODING.UTF8));                Response.ContentType = "APPLICATION/OCTET-STREAM;CHARSET=GBK";                Response.BinaryWrite (Bytefile);                      Response.End (); }}} has been used this way before, butA user uploaded a 700Mb file times memory overflow problem, analyzed for a reason, the user's memory only 256M, and download the file to create a memory stream, resulting in memory overflow.             Solution: 1>writefile block download, is to download a specified number of multiple pieces each time;             2> the way through hyperlinks; Lbldownload.text = "<a href=" + drv["VPath"]. ToString () + "' > Download </a>" Below are four ways to implement file downloads: 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 TransmitFile for response objects to address the use of Response.bina         Rywrite downloading more than 400MB files causes the Aspnet_wp.exe process to recycle without successfully downloading the issue.        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 chunked 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 reads the file every time, only 100K is read, 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;//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 (); }}//stream download protected void Button4_Click (object sender, EventArgs e) {string fileName = "Aaa.txt";//Client The file name of the end-save string FilePath = Server.MapPath ("Download/aaa.txt"),///path/////////download files as character stream FileStream fs = new F        Ilestream (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 (); }}

C # Several ways to implement file downloads

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.