I am trying to stream a large file in webforms from an HttpHandler. It doesn't seem to work because its not streaming the file. Instead its reading the file into memory then sends it back to the client. I look all over for a solution and the solution are telling me that they stream the file when they are doing the same thing. My solution that stream is this:
using (Stream fileStream = File.OpenRead(path))
{
context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(360.0));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.AppendHeader("Content-Type", "video/mp4");
context.Response.AppendHeader("content-length", file.Length);
byte[] buffer = new byte[1024];
while (true)
{
if (context.Response.IsClientConnected)
{
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
context.Response.OutputStream.Write(buffer, 0, bytesRead);
context.Response.Flush();
}
else
{
break;
}
}
context.Response.End();
}
What is happening is for small files if I debug the code, it will play the video but not until it reaches the context.Respond.End() line. But for large files this will not work because it is storing the whole file in memory which will bring issues.
IHttpAsyncHandler
and reading from the disk asynchronously. – Archibold