Home > Mobile >  .NET 7 System.IO.FileNotFoundException: Could not find file
.NET 7 System.IO.FileNotFoundException: Could not find file

Time:12-02

This is my first time asking around here, so sorry if it's not worded very well.

I have a blazor WebAssembly project with MudBlazor, and when I try to upload files to save them into a database, it appears the next error message in the browser console.
System.IO.FileNotFoundException: Could not find file

When the user uploads the files I call the next method to save the files into IList<IBrowserFile>.

IList<IBrowserFile> Files = new List<IBrowserFile>();
private void OnInputFileChanged(InputFileChangeEventArgs e)
    {
        var files = e.GetMultipleFiles();
        foreach(var file in files)
        {
            Files.Add(file);
        }
    }

Once the user has uploaded all the files, they click on a button that call the next method to upload it into a database.

[Inject] protected ISnackbar Snackbar { get; set; } = default!;
private async void Upload()
    {

        List<string>? notUploadFiles = null;
        foreach(var file in Files)
        {
            byte[] fileBytes = File.ReadAllBytes(destPath   file.Name);
            string extn = new FileInfo(file.Name).Extension;

            var addArchivoTarea = new AddArchivoTareaRequestDTO(Tarea.Id, fileBytes, extn);
            var successResponse = await HttpTareas.AddArchivoToTareaAsync(addArchivoTarea);

            if (!successResponse)
            {
                notUploadFiles.Add(file.Name);
            }
        }

        if(notUploadFiles is not null) {
            Snackbar.Configuration.SnackbarVariant = Variant.Filled;
            Snackbar.Add("The following files could not be uploaded:", Severity.Info);

            Snackbar.Configuration.SnackbarVariant = Variant.Outlined;
            foreach (var file in notUploadFiles)
            {
                Snackbar.Add(file, Severity.Error);
            }

            //Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter;
            //Snackbar.Add("TODO: Upload your files!", Severity.Normal);
            MudDialog.Close(DialogResult.Ok(true));
        }

        Snackbar.Add("All files have been successfully uploaded", Severity.Success);
        MudDialog.Close(DialogResult.Ok(true));
    }

I don't know where is the problem, any idea?

CodePudding user response:

The uploaded files are not in the file system, they are in-memory only. The way to access the raw data would be something like:

        byte[] fileBytes;

        using (Stream s = file.OpenReadStream())
        {
            MemoryStream ms = new MemoryStream();
            await s.CopyToAsync(ms);
            fileBytes= ms.ToArray();
        }
  • Related