Search code examples
blazor-webassemblysystem.io.file

Blazor Wasm file upload: System.IO.Filestream keeps adding (preceding) the rootfolder ('/') to the pathstring when instantiating a new FileStream


Trying to upload files from my form <EditForm> with <InputFile OnChange="SaveFilesAsync" multiple></InputFile>. The path I want to use keeps being overwritten by System.IO-logic by adding the AppDomain.CurrentDomain.BaseDirectory, which is root / in this case to my path string, adding it as a first character, provoking an error.

Here are the code blocks. Note that for debugging purposes I in the and simply hard coded the path string. Initially I was trying to load the root path from appsettings, doing a Path combine and so on.

<InputFile OnChange="SaveFilesAsync" multiple></InputFile> calls

private async Task SaveFilesAsync(InputFileChangeEventArgs inputFileChangeEventArgs)
{
    foreach (var file in inputFileChangeEventArgs.GetMultipleFiles())
    {
Stream stream = file.OpenReadStream(maxAllowedSize: 1024 * 1024 * 300);

using (var fileStream = new FileStream(@"C:/Databanken/Lovap/1.png", FileMode.Create))

This generates an error

"Could not find a part of the path '/C:/Databanken/Lovap/1.png'

Note the / that suddenly appeared for the C. Why? How to avoid this?

Expected behavior? I want to be able to store the files on the location of my choosing.

Also, as not an unimportant aside. If I do just use AppDomain.CurrentDomain.BaseDirectory + file.Name. The code runs but in the end I can't find the file anywhere. I would have expected to find it somewhere in the bin-directory (or subdirectories). So I'm really puzzled here.


Solution

  • You're confusing Blazor Server en blazor wasm. This is not possible in blazor wasm, it is possible in Blazor server however. Here's an example and information about how to do it and what is possible. And here's an explanation with regard to the file you couldn't find.