简体   繁体   English

如何在 Blazor WebAssembly 中获取 static 图像文件的文件路径列表?

[英]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.我试图在 Blazor WebAssembly 项目的 wwwroot 文件夹中获取 static 文件的列表。 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'. System.IO.DirectoryNotFoundException:找不到路径“/wwwroot\images”的一部分。

What am I doing wrong?我究竟做错了什么? Thank you.谢谢你。

My first thought was that Directory.GetFiles() shouldn't be supported on Blazor WebAssembly - you are not allowed on the filesystem.我的第一个想法是 Blazor WebAssembly 不应该支持Directory.GetFiles() - 不允许在文件系统上使用。
But running System.IO.Directory.GetDirectories(".") gives this output:但是运行System.IO.Directory.GetDirectories(".")给出了这个 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.但是它们都不包含 wwwroot 和您所追求的内容。

So you can use Http.GetStreamAsync() or Http.GetByteArrayAsync() to get the contents of an image file you already know the name of .因此,您可以使用Http.GetStreamAsync()Http.GetByteArrayAsync()来获取您已经知道名称的图像文件的内容。 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). (我知道您可以将 ISS 配置为允许“浏览”文件夹,但这违反了最佳实践,并让您解析 HTML)。

If you do want to scan a folder, build an API to do so.如果您确实想要扫描文件夹,请构建 API 来执行此操作。 You need to run that on the server.您需要在服务器上运行它。

Please get "images" directory path like below:请获取如下所示的“图像”目录路径:

string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images");
string[] images = Directory.GetFiles(folderPath, "*.jpg");

Hope it will work.希望它会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM