OutOfMemoryException when send big file 500MB using FileStream ASPNET
I've created download page which allows user to download up to 4gb (may be more) few months ago. Here is my working snippet:
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();
}
}
Read Big TXT File, Out of Memory Exception
Just use File.ReadLines which returns an IEnumerable<string>
and doesn't load all the lines at once to the memory.
foreach (var line in File.ReadLines(_filePath))
{
//Don't put "line" into a list or collection.
//Just make your processing on it.
}
Reading large file using byte[] gives error
Instead of reading the whole file into memory just pass a stream to ComputeHash
using(var file = File.Open(path,FileMode.Open))
{
hashValue = hashString.ComputeHash(file);
}
Related Topics
Monitoring Garbage Collector in C#
How Should You Diagnose the Error Sehexception - External Component Has Thrown an Exception
Identifying Nhibernate Proxy Classes
C# How to Loop User Input Until the Datatype of the Input Is Correct
Thread Safety of a Dictionary<Tkey, Tvalue>
Sorting an Array Related to Another Array
Frombluetoothaddressasync Iasyncoperation Does Not Contain a Definition for 'Getawaiter' Error
Are Ienumerable Linq Methods Thread-Safe
Task.Factory.Startnew with Async Lambda and Task.Waitall
How to Get Text Between Nested Parentheses
A Pattern to Pause/Resume an Async Task
How to Detect If MAChine Is Joined to Domain
Why Is This Code Invalid in C#