2011-05-13 39 views
2

使用.NET 4.0,IIS 7.5(Windows Server 2008 R2)。我想流出一個大約10 MB的二進制內容。內容已經在MemoryStream中。我想知道IIS7是否會自動分塊輸出流。從接收流的客戶端,這兩種方法之間有任何區別:ASP.NET Streaming Output:1個單獨大塊vs X個小塊?

//#1: Output the entire stream in 1 single chunks 
Response.OutputStream.Write(memoryStr.ToArray(), 0, (int) memoryStr.Length); 
Response.Flush(); 

//#2: Output by 4K chunks 
byte[] buffer = new byte[4096]; 
int byteReadCount; 
while ((byteReadCount = memoryStr.Read(buffer, 0, buffer.Length)) > 0) 
{ 
    Response.OutputStream.Write(buffer, 0, byteReadCount); 
    Response.Flush(); 
} 

在此先感謝您的任何幫助。


我沒有嘗試通過原始數據流的第二條建議。內存流實際上是從Web請求的響應流填充的。下面是代碼,

HttpWebRequest webreq = (HttpWebRequest) WebRequest.Create(this._targetUri); 
using (HttpWebResponse httpResponse = (HttpWebResponse)webreq.GetResponse()) 
{ 
    using (Stream responseStream = httpResponse.GetResponseStream()) 
    { 
     byte[] buffer = new byte[4096]; 
     int byteReadCount = 0; 
     MemoryStream memoryStr = new MemoryStream(4096); 
     while ((byteReadCount = responseStream.Read(buffer, 0, buffer.Length)) > 0) 
     { 
     memoryStr.Write(buffer, 0, byteReadCount); 
     } 
     // ... etc ... // 
    } 
} 

你認爲它可以安全地傳遞到responseStream Response.OutputStream.Write()?如果是的話,你能提出一個經濟的方法嗎?如何發送ByteArray +確切的流長度到Response.OutputStream.Write()?

+0

您是否會多次提供該內容? – 2011-05-13 16:40:56

+0

最有可能一次。 – Polymerase 2011-05-16 18:48:27

回答

2

第二個選項是最好的一個,因爲ToArray實際上會創建存儲在MemoryStream中的內部數組的副本。

但是,您最好也可以使用memoryStr.GetBuffer(),它將返回對此內部數組的引用。在這種情況下,您需要使用memoryStr.Length屬性,因爲GetBuffer()返回的緩衝區通常比存儲的實際數據大(它通過塊分配塊,而不是逐字節)。

請注意,最好將原始數據作爲流直接傳遞到ASP.NET輸出流,而不是使用中間MemoryStream。這取決於你如何獲得你的二進制數據。

如果您經常使用完全相同的內容,另一種選擇是將此MemoryStream保存到物理文件(使用FileStream),並在所有後續請求上使用Response.TransmitFile。 Response.TransmitFile使用低級別的Windows套接字層,發送文件沒有更快的速度。

+0

非常感謝您的詳盡答案先生。我已經使用memoryStr.GetBuffer()應用了您的建議。剛剛進行了迴歸測試,結果非常完美。 – Polymerase 2011-05-17 21:06:49