Home > Enterprise >  How do I read a text file as a string on ASP.net/blazor?
How do I read a text file as a string on ASP.net/blazor?

Time:04-17

So, I have a text file I need to read. However, no matter how I try to word its path, I can't seem to be able to do so using System.IO.File.ReadAllText(); I can't seem to be able to figure out the current directory, and whatever System.IO.Directory.GetCurrentDirectory() spits out doesn't have any files; and whatever I try to put as a path inevitably returns an exception bearing the message "Could not find file "; and moving the file doesn't seem to help.

The microsoft docs suggest usage of a poorly-documented Server object, but that just raises an error and since they don't really explain what it's supposed to do I'm not really sure what I'm supposed to do; even weirder still is that stylesheet references and all work just fine - it's C# that doesn't like how I write my paths.

There's probably a rather simple fix. I've been advised to use <ItemGroup>s in the csproj file, but that doesn't seem to lead to any tangible result.

Example of one of my first attempts, with state.txt directly in the Client folder:

@page "/"

<div class=galaxy>
@System.IO.Path.GetFullPath(@"~\"   System.IO.Directory.GetCurrentDirectory())
@Main()
</div>
@code {
    SaveNode state;
    string Main()
    {
        try
        {
            System.IO.File.ReadAllText(@"~\state.txt");
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
}

CodePudding user response:

and whatever System.IO.Directory.GetCurrentDirectory() spits out doesn't have any files;

That means you are on Blazor WebAssembly. You can't "read" files there, you will have to download them. Put the file in wwwroot and don't use ~.

  //System.IO.File.ReadAllText(@"~\state.txt");
  using var stream = await httpClient.GetStreamAsync("state.txt");
  // use async I/O on the stream

CodePudding user response:

You can access files in wwwroot folder like this

@inject IWebHostEnvironment webHostEnvironment;

<div class=galaxy>
    @System.IO.File.ReadAllText(System.IO.Path.Combine(webHostEnvironment.WebRootPath, "state.txt"))
</div>

If you have some folder in wwwroot then like this

@inject IWebHostEnvironment webHostEnvironment;

<div class=galaxy>
    @System.IO.File.ReadAllText(System.IO.Path.Combine(webHostEnvironment.WebRootPath, "yourfolder/state.txt"))
</div>

If your project is WASM then

@inject HttpClient httpClient;

<div class=galaxy>
    @fileText
</div>


string fileText;

protected override async Task OnInitializedAsync()
{
    fileText = await ReadFile(); 
}

private async Task<string> ReadFile()
{
    HttpResponseMessage response = await httpClient.GetAsync("state.txt");
    HttpContent content = response.Content;

    return await content.ReadAsStringAsync();
}
  • Related