Я использую Filestream для чтения большой файл (> 500 МБ), и я получаю 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 в порядке, все право.
Проблема следующая:
Считайте толстый большой файл в диске (> 500 МБ) в байте [] и отправьте байты в Ответ (asp.net) для загрузки это.
Когда использование
http://www.yoda.arachsys.com/csharp/readbinary.html
public static byte[] ReadFully
Я получаю ошибку: OutOfMemoryException...
Если лучший BufferedStream, чем Поток (FileStream, MemoryStream...)??
Используя BufferedStream, я могу считать большой файл 700 МБ?? (любое исходное использование примера кода BufferedStream для загрузки большой файл)
Я думаю, это - вопрос: Не, "как считать файл 500 МБ в память?", Но, "как отправить большой файл в Ответный поток 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/
Какие-либо предложения, комментарии, источник примера кода??
Несколько месяцев назад я создал страницу загрузки, которая позволяет пользователю скачивать до 4gb (может быть больше). Вот мой рабочий фрагмент:
private void TransmitFile(string fullPath, string outFileName)
{
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
// Identify the file to download including its path.
string filepath = fullPath;
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + outFileName);
Response.AddHeader("Content-Length", iStream.Length.ToString());
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}
}
Вам не нужно держать весь файл в памяти, просто читайте его и записывайте в поток ответа в цикле.