如何在Blazor WebAssembly中获取静态图像文件的文件路径列表? [英] How can I get a list of file paths for static image files in Blazor WebAssembly?

查看:662
本文介绍了如何在Blazor WebAssembly中获取静态图像文件的文件路径列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取Blazor WebAssembly项目中wwwroot文件夹内的静态文件列表.到目前为止,这是我尝试过的:

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");

我收到此错误:

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:找不到路径'/wwwroot \ images'的一部分.

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

我做错了什么?谢谢.

推荐答案

我的第一个想法是Blazor WebAssembly不应该支持Directory.GetFiles()-文件系统上不允许您使用.
但是运行System.IO.Directory.GetDirectories(".")会给出以下输出:

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

是您可以获取的一些预打包的文件和文件夹.但是它们都不包含wwwroot和您要查找的内容.

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

因此您可以使用Http.GetStreamAsync()Http.GetByteArrayAsync()来获取图像文件的内容,而您已经知道该文件的名称.没有直接扫描文件夹的方法:一种安全功能. (我知道您可以将ISS配置为允许浏览"文件夹,但这违背了最佳实践,并为您提供了HTML解析的语言.)

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).

如果您确实要扫描文件夹,请构建一个API来进行扫描.您需要在服务器上运行它.

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

这篇关于如何在Blazor WebAssembly中获取静态图像文件的文件路径列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆