2012-12-14 292 views
2

我试图从SharePoint下载文件。 经过一番研究,我得到了这个,它说如果我们使用缓冲区,性能会更好。关于流的困惑

备注 - 文件是SPFILE

using (System.IO.Stream strm = file.OpenBinaryStream()) 
{ 
    byte[] buffer = new byte[BUFFER_SIZE]; 
    int bytesRead; 
    do 
    { 
     bytesRead = strm.Read(buffer, 0, BUFFER_SIZE); 
     response.OutputStream.Write(buffer, 0, bytesRead); 
     response.Flush(); 
    } while (bytesRead > 0); 
} 

一旦我们分配像response.BinaryWrite(file.OpenBinary());,我们是否在STRM对象全码流(开始消耗RAM)?假设这个文件是10MB,那么这个strm在RAM中是10MB?

或者一旦我们开始阅读,它会开始消耗内存? bytesRead = strm.Read(buffer, 0, BUFFER_SIZE);

回答

3

Stream是管,而不是一个桶;它不会(通常)“包含”数据 - 它只是对数据管理访问。在该示例而言,通过应用程式随时加载的数据是BUFFER_SIZE字节(加上任何其它层中使用的任何其它缓冲液)。

您在每次写入时也不需要Flush()(尽管末尾的Flush()可能是合适的)。

你有什么是好的;我唯一要说的是,你可以在最近的.NET版本中简化它:

using (System.IO.Stream strm = file.OpenBinaryStream()) 
{ 
    strm.CopyTo(response); 
    // response.Flush(); // optional: only included because it is in the question 
} 
+0

>感谢您的回答。 如果我直接做** response.BinaryWrite(file.OpenBinary()); **,而不是循环?它会有内存问题?如果你不想循环,使用CopyTo从 – kevin

+0

@kevin,如图所示 –