Live demo | Full example on GitHub
Your Blazor app lets people save a file for offline use. It works with a 2 MB photo. Then someone picks a 200 MB video, and your app has to find 200 MB of .NET memory to hold it.
Most of the time the app does not need those bytes in .NET at all. It only wants them moved from one place to another. The browser can do that itself.
This article saves the same file two ways and compares the .NET memory each one takes. You need the .NET 10 SDK and a browser.
Where the file goes
The origin private file system (OPFS) is file storage that belongs to your site. It needs no permission prompt, and other sites cannot read it. It does not show up as a normal folder on the user's disk.
Set up
dotnet new blazorwasm -o LargeFiles --empty
cd LargeFiles
dotnet add package SpawnDev.SpawnJS
dotnet add package SpawnDev.SpawnJS.Blazor
Replace Program.cs:
using LargeFiles;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using SpawnDev.SpawnJS;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddSpawnJSRuntime();
await builder.Build().SpawnJSRunAsync();
Add these lines to _Imports.razor:
@using SpawnDev.SpawnJS
@using SpawnDev.SpawnJS.JSObjects
Through .NET
// The usual way: the whole file becomes a byte[] in .NET.
async Task<long> SaveThroughDotNet(Blob file, FileSystemWritableFileStream target)
{
using var buffer = await file.ArrayBuffer();
byte[] bytes = buffer.ReadBytes();
var used = GC.GetTotalMemory(false);
await target.Write(bytes);
await target.Close();
return used;
}
ReadBytes() copies the whole file into a .NET array. Write then hands it back to the browser.
Streamed
// The browser moves the bytes. .NET only says where from and where to.
async Task<long> SaveStream(Blob file, FileSystemWritableFileStream target)
{
using var stream = file.Stream();
await stream.PipeTo(target); // also closes the target
return GC.GetTotalMemory(false);
}
PipeTo connects the file's stream to the storage file's stream. The bytes go from one to the other inside the browser, and your C# code waits for it to finish.
Open the storage file
Both versions write to the same place:
async Task Run(Func<Blob, FileSystemWritableFileStream, Task<long>> save)
{
busy = true;
result = "Saving...";
await Task.Delay(50); // let the page draw
try
{
using var file = GetChosenFile() ?? MakeTestFile();
using var navigator = new Navigator();
using var storage = navigator.Storage;
using var folder = await storage.GetDirectory();
using var handle = await folder.GetFileHandle(FileName, create: true);
using var target = await handle.CreateWritable();
GC.Collect();
var before = GC.GetTotalMemory(true);
var after = await save(file, target);
using var saved = await handle.GetFile();
result = $"Saved {saved.Size / 1048576.0:F1} MB. .NET memory grew by {Math.Max(0, after - before) / 1048576.0:F1} MB.";
await folder.RemoveEntry(FileName);
}
catch (Exception ex)
{
result = $"Could not save: {ex.Message}";
}
GC.Collect();
busy = false;
}
The folder and file handles are wrappers around live browser objects, so each one gets a using.
What we measured
For a 200 MB file:
| Way | .NET memory grew by |
|---|---|
| Through .NET | 200 MB |
| Streamed | 0.0 MB |
The browser still uses memory of its own while it copies. The difference is that your .NET heap does not grow with the size of the file.
Play a video without loading it
Back to that 200 MB video. To play it, your app still does not need the bytes. A video player needs a URL, and URL.CreateObjectURL makes one for any Blob: a file the user picked, a file from storage, or one you downloaded.
async Task PlayFromStorage()
{
busy = true;
result = "Saving...";
await StopVideo();
try
{
using var file = GetChosenFile() ?? await GetSampleVideo();
using var navigator = new Navigator();
using var storage = navigator.Storage;
using var folder = await storage.GetDirectory();
using var handle = await folder.GetFileHandle(VideoName, create: true);
using var target = await handle.CreateWritable();
GC.Collect();
var before = GC.GetTotalMemory(true);
using var stream = file.Stream();
await stream.PipeTo(target);
using var saved = await handle.GetFile();
videoUrl = URL.CreateObjectURL(saved);
result = $"Playing {saved.Size / 1048576.0:F1} MB from storage. .NET memory grew by {Math.Max(0, GC.GetTotalMemory(false) - before) / 1048576.0:F1} MB.";
}
catch (Exception ex)
{
result = $"Could not play: {ex.Message}";
}
busy = false;
}
Even the sample clip is never a .NET array. The response from fetch becomes a Blob, and only a reference to it reaches C#:
// Even the download stays in the browser: the response becomes a Blob, not a byte[].
async Task<Blob> GetSampleVideo()
{
using var response = await JS.Fetch("BigBuckBunny-30.mp4");
if (!response.Ok) throw new Exception("no sample video found, choose a file instead");
return await response.Blob();
}
To run this yourself, put a video in wwwroot as BigBuckBunny-30.mp4, for example the clip from the example repo, or choose your own file on the page.
The page hands that URL to an ordinary video element:
<video src="@videoUrl" controls></video>
The player reads the file from storage as it needs it, and none of the video enters .NET. Revoke the URL when you are done with it, so the browser can let go of the file:
// An object URL keeps its file in use until it is revoked.
async Task StopVideo()
{
if (videoUrl is null) return;
URL.RevokeObjectURL(videoUrl);
videoUrl = null;
using var navigator = new Navigator();
using var storage = navigator.Storage;
using var folder = await storage.GetDirectory();
await folder.RemoveEntry(VideoName);
}
Bring data into .NET only when .NET needs it
The wrappers work with both kinds of data. Write on the storage file takes .NET data, such as a byte[] or a string, and browser data, such as a Blob, an ArrayBuffer or a typed array. If your C# code made the data or has to work on it, pass the .NET type. If you are only moving it, pass the browser object and leave the bytes where they are.
When you do need the bytes
If your code has to look at the contents, read it in pieces. Blob.Slice(start, end) gives you part of a file, so you only hold one piece at a time.
The whole page
Replace Pages/Home.razor with this:
@page "/"
@inject SpawnJSRuntime JS
@implements IAsyncDisposable
<main>
<h1>Where does the file go?</h1>
<p>Both buttons save the same file to this browser's private storage, then delete it. Compare how much .NET memory each one takes.</p>
<p><label>Your own file, or leave empty for a @SizeMB MB test file: <input id="pick" type="file" /></label></p>
<button id="copy" disabled="@busy" @onclick="() => Run(SaveThroughDotNet)">Save through .NET</button>
<button id="stream" disabled="@busy" @onclick="() => Run(SaveStream)">Stream it</button>
<p id="result" role="status">@result</p>
<h2>Play a video from storage</h2>
<p>Saves a video to storage and plays it from there. Leave the file above empty to use a 30 second Big Buck Bunny clip.</p>
<button id="play" disabled="@busy" @onclick="PlayFromStorage">Play it</button>
@if (videoUrl is not null)
{
<p><video id="video" src="@videoUrl" controls autoplay muted></video></p>
}
<p><small>Big Buck Bunny (c) 2008 Blender Foundation, <a href="https://peach.blender.org">peach.blender.org</a>. Sunflower version by Janus Bager Kristensen, 2013. <a href="https://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.</small></p>
</main>
@code {
const int SizeMB = 200;
const string FileName = "test.bin";
const string VideoName = "video";
string? videoUrl;
bool busy;
string result = "";
// The usual way: the whole file becomes a byte[] in .NET.
async Task<long> SaveThroughDotNet(Blob file, FileSystemWritableFileStream target)
{
using var buffer = await file.ArrayBuffer();
byte[] bytes = buffer.ReadBytes();
var used = GC.GetTotalMemory(false);
await target.Write(bytes);
await target.Close();
return used;
}
// The browser moves the bytes. .NET only says where from and where to.
async Task<long> SaveStream(Blob file, FileSystemWritableFileStream target)
{
using var stream = file.Stream();
await stream.PipeTo(target); // also closes the target
return GC.GetTotalMemory(false);
}
async Task Run(Func<Blob, FileSystemWritableFileStream, Task<long>> save)
{
busy = true;
result = "Saving...";
await Task.Delay(50); // let the page draw
try
{
using var file = GetChosenFile() ?? MakeTestFile();
using var navigator = new Navigator();
using var storage = navigator.Storage;
using var folder = await storage.GetDirectory();
using var handle = await folder.GetFileHandle(FileName, create: true);
using var target = await handle.CreateWritable();
GC.Collect();
var before = GC.GetTotalMemory(true);
var after = await save(file, target);
using var saved = await handle.GetFile();
result = $"Saved {saved.Size / 1048576.0:F1} MB. .NET memory grew by {Math.Max(0, after - before) / 1048576.0:F1} MB.";
await folder.RemoveEntry(FileName);
}
catch (Exception ex)
{
result = $"Could not save: {ex.Message}";
}
GC.Collect();
busy = false;
}
async Task PlayFromStorage()
{
busy = true;
result = "Saving...";
await StopVideo();
try
{
using var file = GetChosenFile() ?? await GetSampleVideo();
using var navigator = new Navigator();
using var storage = navigator.Storage;
using var folder = await storage.GetDirectory();
using var handle = await folder.GetFileHandle(VideoName, create: true);
using var target = await handle.CreateWritable();
GC.Collect();
var before = GC.GetTotalMemory(true);
using var stream = file.Stream();
await stream.PipeTo(target);
using var saved = await handle.GetFile();
videoUrl = URL.CreateObjectURL(saved);
result = $"Playing {saved.Size / 1048576.0:F1} MB from storage. .NET memory grew by {Math.Max(0, GC.GetTotalMemory(false) - before) / 1048576.0:F1} MB.";
}
catch (Exception ex)
{
result = $"Could not play: {ex.Message}";
}
busy = false;
}
// Even the download stays in the browser: the response becomes a Blob, not a byte[].
async Task<Blob> GetSampleVideo()
{
using var response = await JS.Fetch("BigBuckBunny-30.mp4");
if (!response.Ok) throw new Exception("no sample video found, choose a file instead");
return await response.Blob();
}
// An object URL keeps its file in use until it is revoked.
async Task StopVideo()
{
if (videoUrl is null) return;
URL.RevokeObjectURL(videoUrl);
videoUrl = null;
using var navigator = new Navigator();
using var storage = navigator.Storage;
using var folder = await storage.GetDirectory();
await folder.RemoveEntry(VideoName);
}
public async ValueTask DisposeAsync() => await StopVideo();
Blob? GetChosenFile()
{
using var document = JS.GetDocument()!;
using var input = document.GetElementById<HTMLInputElement>("pick")!;
using var files = input.Files;
return files?.FirstOrDefault();
}
// One MB of data, repeated. The browser holds it; nothing large is made in .NET.
static Blob MakeTestFile()
{
using var block = new Blob(new[] { new byte[1048576] });
return new Blob(Enumerable.Repeat(block, SizeMB));
}
}
Run it
Run dotnet run in your project, or clone the finished one:
git clone https://github.com/LostBeard/SpawnDev.Examples
cd SpawnDev.Examples/LargeFiles
dotnet run
Top comments (0)