如何从 Blazor WebAssembly 中的目录读取文件 [英] How to read files from a directory in Blazor WebAssembly

查看:280
本文介绍了如何从 Blazor WebAssembly 中的目录读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发 .NET Standard 2.1 Blazor WebAssembly 应用程序.我尝试从我的 wwwroot 目录中读取文件路径.

I'm currently working on a .NET Standard 2.1 Blazor WebAssembly application. I try to read file paths from my wwwroot directory.

Blazor WebAssembly 应用程序不是由 Asp.NET Core 托管的.

The Blazor WebAssembly App is NOT Asp.NET Core hosted.

我尝试从 Program.cs 中的 Main 方法中读取以 .js 结尾的所有文件路径,如下所示:

I try to read all file paths with the ending .js from my Main method in the Program.cs like this:

var filePaths = ReadWwwRootJSFilePaths();
private static string[] ReadWwwRootJSFilePaths()
        {
            Console.WriteLine("CurrentDirectory: " + Directory.GetCurrentDirectory());
            var dir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "js");
            Console.WriteLine("dir: " + dir);
            var files = Directory.GetFiles(dir);
            foreach (string file in files)
            {
                Console.WriteLine("file: " + file);
            }
            return files;
        }

当我运行它时,我只在浏览器中收到一条错误消息:System.IO.DirectoryNotFoundException

When I run this I only get an error message in my browser: System.IO.DirectoryNotFoundException

你知道如何解决这个问题吗?您知道如何从 Blazor WASm(非 ASP.NET Core 托管)应用程序中的 wwwroot 目录读取文件路径吗?

Do you know how to solve this problem? Do you know how to read file paths from the wwwroot dir in a Blazor WASm (not ASP.NET Core hosted) application?

也许我还不太了解 Blazor WebAssembly(不是 ASP.NET Core 托管)的概念.是否真的可以使用 C# .NET Core 功能?

Perhaps yet I don't quite get the concept of Blazor WebAssembly (not ASP.NET Core hosted). Is it actually possible to use C# .NET Core functionalities?

推荐答案

是的,您可以简单地对 wwwroot 中的文件执行 HTTP 调用.

Yes, you can simply perform HTTP calls to the files in your wwwroot.

要查看实际操作,请创建一个 WebAssembly 独立项目,其中 FetchData 调用位于 wwwroot 中的 json 文件.这是一些代码:

To see this done in action, create a WebAssembly stand alone project, in which the FetchData calls a json file located in the wwwroot. Here's some code:

protected override async Task OnInitializedAsync()
    {
        forecasts = await Http.GetJsonAsync<WeatherForecast[]>("sample-data/weather.json");
    }

这篇关于如何从 Blazor WebAssembly 中的目录读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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