ASP.NET Core  

How to Handle File Streaming in ASP.NET Core for Large Files

Introduction

When working with ASP.NET Core Web API, handling large files such as videos, PDFs, backups, or reports can be challenging. If not implemented properly, large file uploads or downloads can consume a lot of memory, slow down your application, or even crash your server.

This is where file streaming in ASP.NET Core becomes very important.

In simple words, file streaming allows you to send or receive files in small chunks instead of loading the entire file into memory at once. This makes your application more efficient, scalable, and reliable.

In this article, you will learn how to handle file streaming in ASP.NET Core for large files step by step using simple language, real-world examples, and practical use cases.

What is File Streaming in ASP.NET Core?

File streaming is a technique where data is processed piece by piece instead of loading everything into memory at once.

Without streaming:

  • Entire file is loaded into RAM

  • High memory usage

  • Risk of application crash

With streaming:

  • File is processed in chunks

  • Low memory usage

  • Better performance

Real-life example:

Think of watching a movie on the internet. You do not download the entire movie before watching. Instead, it plays while downloading in parts. That is streaming.

Step 1: Create ASP.NET Core Web API Project

dotnet new webapi -n FileStreamingDemo
cd FileStreamingDemo

Step 2: Enable Large File Upload Support

using Microsoft.AspNetCore.Http.Features;

builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = long.MaxValue;
});

Step 3: Upload Large Files Using Streaming

[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase
{
    [HttpPost("upload")]
    public async Task<IActionResult> Upload()
    {
        var filePath = Path.Combine("Uploads", "largefile.dat");

        Directory.CreateDirectory("Uploads");

        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await Request.Body.CopyToAsync(stream);
        }

        return Ok("File uploaded successfully");
    }
}

Step 4: Download Large Files Using Streaming

[HttpGet("download")]
public IActionResult Download()
{
    var filePath = Path.Combine("Uploads", "largefile.dat");

    if (!System.IO.File.Exists(filePath))
        return NotFound();

    var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

    return File(stream, "application/octet-stream", "largefile.dat");
}

Step 5: Stream File with Buffer (Advanced Control)

[HttpGet("download-buffered")]
public async Task DownloadBuffered()
{
    var filePath = Path.Combine("Uploads", "largefile.dat");

    Response.ContentType = "application/octet-stream";
    Response.Headers.Add("Content-Disposition", "attachment; filename=largefile.dat");

    using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[81920];
    int bytesRead;

    while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
    {
        await Response.Body.WriteAsync(buffer, 0, bytesRead);
        await Response.Body.FlushAsync();
    }
}

Step 6: Validate File Size and Type

if (Request.ContentLength > 500_000_000)
{
    return BadRequest("File too large");
}

Step 7: Secure File Upload

var fileName = Path.GetRandomFileName();
var safePath = Path.Combine("Uploads", fileName);

Step 8: Real-World Example

In a video upload system:

  • User uploads video using streaming API

  • Server writes file directly to disk

  • Users download video using streaming endpoint

This avoids memory overload and improves performance.

Common Mistakes to Avoid

  • Using IFormFile for very large files

  • Not setting size limits

  • Loading full file into memory

Advantages of File Streaming

  • Efficient memory usage

  • Supports large files

  • Better performance

Disadvantages of File Streaming

  • Slightly more complex logic

Summary

File streaming in ASP.NET Core is essential for handling large files efficiently. By reading and writing data in chunks, you reduce memory usage and improve application performance. Using proper streaming techniques, validation, and security practices ensures your application remains fast, scalable, and production-ready.