ASP.NET解決網頁下載檔案過大的問題,使用stream方式下載

這個問題很久之前就有人問過了,最近又有人問到,就把它放在我的blog裡
一般下載檔案都會用Response.WriteFile(FullName)
這樣會造成 Aspnet_wp.exe 暫存了太大空間而導致下載失敗,建議採用stream方式下載

這個問題很久之前就有人問過了,最近又有人問到,就把它放在我的blog裡

一般下載檔案都會用Response.WriteFile(FullName)

這樣會造成 Aspnet_wp.exe 暫存了太大空間而導致下載失敗,建議採用stream方式下載

asp.net(c#)

部分程式碼

        System.IO.Stream iStream = null;

        //以10K為單位暫存:
        byte[] buffer = new Byte[10000];

        int length;

        long dataToRead;

        // 制定文件路徑.
        string filepath = Server.MapPath("~/aaa.rar");

        //  得到文件名.
        string filename = System.IO.Path.GetFileName(filepath);

        try
        {
            // 打開文件.
            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);


            // 得到文件大小:
            dataToRead = iStream.Length;

            Response.ContentType = "application/x-rar-compressed";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename));

            while (dataToRead > 0)
            {
                //保証client連接
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, 10000);

                    Response.OutputStream.Write(buffer, 0, length);

                    Response.Flush();

                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }

                else
                {
                    //结束循環
                    dataToRead = -1;
                }

            }

        }

        catch (Exception ex)
        {
            // error
            Response.Write("Error : " + ex.Message);
        }

        finally
        {
            if (iStream != null)
            {
                //關閉文件
                iStream.Close();
            }

        }

參考網址:

http://www.blueshop.com.tw/board/show.asp?subcde=BRD200706131110357NX&fumcde=

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20080506151701ZMH&fumcde=FUM20041006161839LRJ