Search code examples
c#web.net-corewebassemblyblazor

Reading server-side files using Blazor


I have a project based on the Blazor sample with a .Client, .Server and .Shared projects. I have a textfile data.txt on the server that I want to be able to read/write using standard StreamReader / System.IO.File methods. Since Blazor runs in a sandbox I guess I can't access the entire filesystem as I would in a normal windows app? I've placed the file in the wwwroot directory, and I can even access the file from the client if a enter url/data.txt in the browser so the file gets served, which I don't want to alow, but trying to read that file as such:

var file = File.ReadAllText("data.txt");

Results in the error:

WASM: [System.IO.FileNotFoundException] Could not find file "/data.txt"

How can I read server-side files and keep them hidden from the client?


Solution

  • Turns out this was easier than I thought. I was approaching it from the wrong angle. To access server side files, create a controller as such:

    using Microsoft.AspNetCore.Mvc;
    
    namespace Favlist.Server.Controllers
    {
        [Route("api/[controller]")]
        public class DataFetcher : Controller
        {
            [HttpGet("[action]")]
            public MyDataClass GetData(string action, string id)
            {
                var str = File.ReadAllText("data.txt");
                return new MyDataClass(str);
            }
        }
    }
    

    And call it within your page like so:

    @using System.IO;
    @page "/dataview"
    @inject HttpClient Http
    
    @if (data == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <p>@data.Name</p>
    }
    
    @functions {
        MyDataClass data;
    
        protected override async Task OnInitAsync()
        {
            data = await Http.GetJsonAsync<MyDataClass>("api/DataFetcher/GetData");
        }
    }
    

    MyDataClass is your custom class containing whatever you need to read/write.

    You can then access files exactly as you normally would, wherever you want on the server. The current directory is your Project.Server root folder.