Search code examples
c#.net-coreblazorblazor-webassemblywwwroot

How can I get a list of file paths for static image files in Blazor WebAssembly?


I'm trying to get a list of the static files inside of my wwwroot folder in a Blazor WebAssembly project. This is what I've tried so far:

string[] images = Directory.GetFiles(@"wwwroot\images", "*.jpg");

I get this error:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
  Unhandled exception rendering component: Could not find a part of the path '/wwwroot\images'.

System.IO.DirectoryNotFoundException: Could not find a part of the path '/wwwroot\images'.

What am I doing wrong? Thank you.


Solution

  • My first thought was that Directory.GetFiles() shouldn't be supported on Blazor WebAssembly - you are not allowed on the filesystem.
    But running System.IO.Directory.GetDirectories(".") gives this output:

    ./tmp
    ./home
    ./dev
    ./proc
    ./zoneinfo
    

    which are some pre-packaged files&folders you can get at. But none of them contain wwwroot and the contents you're after.

    So you can use Http.GetStreamAsync() or Http.GetByteArrayAsync() to get the contents of an image file you already know the name of. There is no direct way to scan a folder: a security feature. (I know you can configure ISS to allow 'browsing' a folder but that goes against best practices and gives you HTML to parse).

    If you do want to scan a folder, build an API to do so. You need to run that on the server.