2013-05-13 35 views
1

我有一個大的XML文件,我從SQL數據庫生成並使用System.Xml.XmlWriter對象流式傳輸到客戶端的Web瀏覽器。問題是,每次用戶點擊網頁時,170MB文件都會在數據庫中生成並再次傳輸。將大型響應流的副本保存到Web服務器上的文件

我想將文件流式傳輸給用戶,以便儘可能快地獲取它,然後將結果保存到Web服務器上的文件中。未來的請求會首先檢查文件是否存在。如果是這樣,它會發送文件而不是調用數據庫。

我的問題:如何將寫入Response.Output對象的內容存儲到文件中?

回答

0

您可以使用一個緩衝,保存數據的一部分到緩衝區,並在同一時間給他們,並將它們保存...這裏有一個例子:

byte[] buffer = new byte[4096]; 
int sourceBytes; 
do 
{ 
    // read it - or fix the buffer content 
    sourceBytes = fs.Read(buffer, 0, buffer.Length); 

    // out put to the client 
    context.Response.OutputStream.Write(buffer, 0, sourceBytes); 
    // saved it to the file. 
    sWriter.Write(buffer, 0, sourceBytes); 

} while (sourceBytes > 0); 
0

也許是這樣的:

var filePath = "c:\\temp\\file.dat"; 
if(System.IO.File.Exists(filePath)) 
{ 
    using(var stream = System.IO.File.OpenRead(filePath)) 
    WriteToResponseStream(stream); 
} 
else 
{ 
    byte[] file = GetFileFromDb(); 
    WriteToResponseStream(new MemoryStream(file)); 
    System.IO.File.WriteAllBytes(filePath, file) 
} 
相關問題