﻿# ASP.NET 回應大型檔案的注意事項

當使用 ASP.NET 回應大型檔案的時候，通常有三種方式可以實做，但使用上有幾個地方要特別注意：

**第一種：使用 [Response.WriteFile()](http://msdn2.microsoft.com/zh-tw/library/system.web.httpresponse.writefile.aspx) 方法**

> ```csharp
> Response.ContentType = "application/download";
> Response.WriteFile(@"C:\VeryBigFile.zip");
> ```
> 
> **注意事項：**
> 
> 1.  當回應過大的檔案時，可能會導致 ASP.NET 的 Worker Proccess 被強制回收，導致下載失敗。參見：[PRB: Response.WriteFile cannot download a large file](https://web.archive.org/web/20090918052438/http://support.microsoft.com:80/kb/812406 "PRB: Response.WriteFile cannot download a large file")
>     
> 2.  使用此方法會支援檔案續傳功能。( HTTP 1.1 )
>     

**第二種：使用 [Response.BinaryWrite()](http://msdn2.microsoft.com/zh-tw/library/system.web.httpresponse.binarywrite.aspx) 方法**

> ```csharp
> Response.ContentType = "application/download";
> Response.BinaryWrite(File.ReadAllBytes(@"C:\VeryBigFile.zip"));
> ```
> 
> **注意事項：**
> 
> 1.  使用此方法會支援檔案續傳功能。( HTTP 1.1 )

**第三種：使用 [Response.TransmitFile()](http://msdn2.microsoft.com/zh-tw/library/system.web.httpresponse.transmitfile.aspx) 方法**

> ```csharp
> Response.ContentType = "application/download";
> Response.TransmitFile(@"C:\VeryBigFile.zip");
> ```
> 
> **注意事項：**
> 
> 1.  當需要回應很大的檔案時，最適合用此方法！因為使用 TransmitFile() 方法不會將檔案內容緩存於記憶體中，執行的效能最好。
>     
> 2.  缺點是使用此方法會讓 ASP.NET 無法支援續傳功能。  
>     

**相關網址**

-   Tracking and Resuming Large File Downloads in ASP.NET  
    [https://web.archive.org/web/20210926211313/http://www.devx.com/dotnet/Article/22533](https://web.archive.org/web/20210926211313/http://www.devx.com/dotnet/Article/22533)  
      
    
-   PRB: Response.WriteFile cannot download a large file  
    [https://web.archive.org/web/20090918052438/http://support.microsoft.com:80/kb/812406](https://web.archive.org/web/20090918052438/http://support.microsoft.com:80/kb/812406)  
      
    
-   HttpResponse.WriteFile 方法 (String)  
    [http://msdn2.microsoft.com/zh-tw/library/dyfzssz9.aspx](http://msdn2.microsoft.com/zh-tw/library/dyfzssz9.aspx)
