with Blazor server app, file I/O is handled by the hosting operating system, and has full access to the servers filesystem.
with Blazor WASM, file I/O is handled by jsinterop to browser javascript.
- the browser supports reading a file selected with the <input type="file"> control or window.showOpenFilePicker()
- the browser supports writing a file via a data url on an anchor or the window.showSaveFilePicker() which give a handle.
the file api is async (returns promise which is not supported by jsinterop serialization), so can not be called directly from Blazor. you should write a javascript function that calls back to a Blazor static method when complete:
// blazor must call with InvokeVoidAsync as a promise is returned.
const readFile = async (assemblyName, methodName) => {
try {
// Always returns an array.
const [handle] = await window.showOpenFilePicker();
const file = await handle.getFile();
const text = await file.text();
await DotNet.invokeMethodAsync(assemblyName, methodName, text);
} catch (err) {
console.error(err.name, err.message);
}
}
// blazor must call with InvokeVoidAsync as a promise is returned.
const saveFile = async (assemblyName, methodName, text) => {
try {
const handle = await window.showSaveFilePicker({
types: [{
accept: {
// Omitted
},
}],
});
const writable = await handle.createWritable();
await writable.write(text);
await writable.close();
await DotNet.invokeMethodAsync(assemblyName, methodName);
} catch (err) {
console.error(err.name, err.message);
}
};