Blazor WASM中Directory.GetFiles报错‘找不到路径的一部分’求助
Blazor WASM获取wwwroot/images下文件名的解决方案
问题根源
Blazor WASM运行在浏览器沙箱环境中,System.IO.Directory/DirectoryInfo这类桌面端文件系统API无法直接访问wwwroot资源——浏览器不允许前端代码直接操作本地文件系统,这类API在WASM环境中执行必然抛出异常。wwwroot下的资源是作为静态HTTP资源供浏览器请求的,而非通过本地文件路径读取。
修复方案
方案一:通过服务器端API动态获取(适合图片目录需动态更新的场景)
如果你的项目是Blazor WASM Hosted模式(带有ASP.NET Core后端),可以在服务器端编写API读取文件列表,再由前端调用:
- 服务器端添加API接口
[ApiController] [Route("api/images")] public class ImagesController : ControllerBase { private readonly IWebHostEnvironment _webHostEnv; public ImagesController(IWebHostEnvironment webHostEnv) { _webHostEnv = webHostEnv; } [HttpGet("list")] public IActionResult GetImageFileNames() { var imageDirPath = Path.Combine(_webHostEnv.WebRootPath, "images"); if (!Directory.Exists(imageDirPath)) { return NotFound("图片目录不存在"); } var fileNames = Directory.GetFiles(imageDirPath, "*.*", SearchOption.AllDirectories) .Select(filePath => Path.GetFileName(filePath)) .ToList(); return Ok(fileNames); } }
- Blazor组件中调用API
public partial class Index { [Inject] private HttpClient Http { get; set; } private List<string> imageFileNames = new(); protected override async Task OnInitializedAsync() { try { imageFileNames = await Http.GetFromJsonAsync<List<string>>("api/images/list"); foreach (var fileName in imageFileNames) { Console.WriteLine(fileName); } } catch (Exception ex) { Console.WriteLine($"加载图片列表失败:{ex.Message}"); } } }
方案二:编译时预生成文件列表(适合图片目录固定、无需动态更新的场景)
如果images目录下的图片是固定不变的,可以通过MSBuild任务在编译时生成包含所有文件名的JSON文件,前端直接读取该静态文件:
- 修改项目.csproj文件
添加MSBuild任务,编译时自动生成wwwroot/images/files.json:
<Target Name="GenerateImageList" BeforeTargets="Build"> <ItemGroup> <ImageFiles Include="wwwroot\images\**\*.*" /> </ItemGroup> <WriteLinesToFile File="wwwroot\images\files.json" Lines="["@(ImageFiles->'"%(Filename)%(Extension)"', ',')"]" Overwrite="true" /> </Target>
- Blazor组件中读取JSON文件
public partial class Index { [Inject] private HttpClient Http { get; set; } private List<string> imageFileNames = new(); protected override async Task OnInitializedAsync() { try { imageFileNames = await Http.GetFromJsonAsync<List<string>>("images/files.json"); foreach (var fileName in imageFileNames) { Console.WriteLine(fileName); } } catch (Exception ex) { Console.WriteLine($"加载图片列表失败:{ex.Message}"); } } }
关键注意点
- Blazor WASM前端代码绝对不能直接使用
System.IO命名空间下的文件系统API,所有资源访问必须通过HTTP请求完成。 - 如果是Standalone模式(无后端),只能使用方案二,或者将图片列表硬编码到组件中。
内容的提问来源于stack exchange,提问作者Vischi
相关产品推荐
相关产品推荐

