3

I have a Blazor WASM (not hosted) project with Todo and TodoList models. 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".

Project structure:

enter image description here

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:

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

Running app throws the exception: Could not find file "/todos.txt". Although I can open the file directly by request https://localhost:44361/todos.txt when the app is running.

Why can't the app find the text file? How can I open and read it?

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
Igor P.
  • 33
  • 1
  • 5

2 Answers2

1

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.

I would use the HttpClient to fetch it.

Mister Magoo
  • 7,452
  • 1
  • 20
  • 35
-1

You can use Http.GetStringAsync(). You can click this link.

Yihui Sun
  • 755
  • 3
  • 5