【发布时间】:2011-03-22 17:28:58
【问题描述】:
我正在使用 Filestream 读取大文件 (> 500 MB),我得到了 OutOfMemoryException。
我使用 Asp.net、.net 3.5、win2003、iis 6.0
我想在我的应用中使用这个:
从 Oracle 读取数据
使用 FileStream 和 BZip2 解压缩文件
读取未压缩的文件并将其发送到asp.net页面进行下载。
当我从磁盘读取文件时,失败!!!并获得 OutOfMemory...
。我的代码是:
using (var fs3 = new FileStream(filePath2, FileMode.Open, FileAccess.Read))
{
byte[] b2 = ReadFully(fs3, 1024);
}
// http://www.yoda.arachsys.com/csharp/readbinary.html
public static byte[] ReadFully(Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
现在,我可以更好地说明我的问题。
使用 FileStream 和 BZip2 解压文件是可以的,一切正常。
问题如下:
在 byte[] 中读取磁盘中的大文件 (> 500 MB) 并将字节发送到 Response (asp.net) 以供下载。
使用时
http://www.yoda.arachsys.com/csharp/readbinary.html
public static byte[] ReadFully
我收到错误:OutOfMemoryException...
如果 BufferedStream 比 Stream (FileStream, MemoryStream, ...) 更好??
使用 BufferedStream ,我可以读取 700 MB 的大文件吗? (任何使用 BufferedStream 下载大文件的示例代码源)
我认为,这就是问题所在:不是“如何将 500mb 文件读入内存?” , 但是“如何将大文件发送到 ASPNET 响应流?”
我通过 Cheeso 找到了这段代码:
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
Response.BufferOutput= false; // to prevent buffering
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
}
}
这是好代码吗?对高性能有何改进??
一位同事说我,使用
Response.TransmitFile(filePath);
现在,另一个问题,更好的 TransmitFile 或 Cheeso 的代码??
多年前,在 msdn 杂志上出现过关于它的精彩文章,但我无法访问 http://msdn.microsoft.com/msdnmag/issues/06/09/WebDownloads/,
更新:您可以使用链接中的webarchive访问:https://web.archive.org/web/20070627063111/http://msdn.microsoft.com/msdnmag/issues/06/09/WebDownloads/
有什么建议、cmets、示例代码源??
【问题讨论】:
标签: asp.net stream download filestream out-of-memory