简体   繁体   English

如何在 Blazor WASM 项目中读取本地文本文件?

[英]How to read a local text file in Blazor WASM project?

I have a Blazor WASM (not hosted) project with Todo and TodoList models.我有一个带有TodoTodoList模型的 Blazor WASM(未托管)项目。 I put a text file in wwwroot folder and try to read it in TodoList constructor by File.ReadAllLines() method passing the path "todos.txt" .我将一个文本文件放在wwwroot文件夹中,并尝试通过传递路径"todos.txt"File.ReadAllLines()方法在TodoList构造函数中读取它。

Project structure:项目结构:

在此处输入图像描述

public class TodoList
{
    public TodoList()
    {
        Todos = new List<Todo>();
        try
        {
            var lines = File.ReadAllLines("todos.txt");
            foreach (string line in lines)
            {
                Todos.Add(new Todo { Title = line });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"{ex.Message}");
        }
    }

    public List<Todo> Todos { get; set; }
}
public class Todo
{
    public string Title { get; set; }
    public bool Checked { get; set; } = false;
}

I create TodoList object in a razor component:我在 razor 组件中创建TodoList object :

@page "/todopage"
...
@code {
    private TodoList todoList = new TodoList();
    ...
}

Running app throws the exception: Could not find file "/todos.txt" .运行应用程序抛出异常:找不到文件“/todos.txt” Although I can open the file directly by request https://localhost:44361/todos.txt when the app is running.虽然我可以在应用程序运行时通过请求https://localhost:44361/todos.txt直接打开文件。

Why can't the app find the text file?为什么应用程序找不到文本文件? How can I open and read it?如何打开并阅读它?

It can't find the file because it is just a resource on the server until you fetch it.它无法找到该文件,因为它只是服务器上的一个资源,直到您获取它。

So, you can use HttpClient to fetch it (you already know the URL) Or you can make it an embedded resource and read it from the resource stream.因此,您可以使用 HttpClient 来获取它(您已经知道 URL),或者您可以将其设为嵌入式资源并从资源 stream 中读取它。

I would use the HttpClient to fetch it.我会使用 HttpClient 来获取它。

You can use Http.GetStringAsync() .您可以使用Http.GetStringAsync() You can click this link .你可以点击这个链接

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

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