24 November 2024
Blazor server Read file

Reading server-side files using Blazor

A little trick that made me lose a lot of time but which turns out to be extremely simple; My initial goal was to open a file in the format Markdown placed in my project. I was creating a small controller to read this file but the solution is simply to use :

System.IO.Directory.GetCurrentDirectory()

And here, by example, I placed my file in the root wwwroot :

$"{System.IO.Directory.GetCurrentDirectory()}
   {@"\wwwroot\news.md"}"
@page "/news"
@using Markdig

@((MarkupString)news)

@code {
   public string news { get; set; }

   protected override async Task OnInitializedAsync()
   {
      var mardownFile = System.IO.File.ReadAllText($"{System.IO.Directory.GetCurrentDirectory()}{@"\wwwroot\news.md"}");

      news = Markdown.ToHtml(mardownFile);
   }
}

 

4 thoughts on “Reading server-side files using Blazor

  1. Pourquoi $”{System.IO.Directory.GetCurrentDirectory()}{@”\wwwroot\news.md”}” plutôt que $”{System.IO.Directory.GetCurrentDirectory()}\wwwroot\news.md” qui est beaucoup plus simple?

    1. Dans ce cas, il faut pas oublier de cumuler le @ devant pour interprétation de l’antislash et le $ pour l’interpolation :

      @$"{System.IO.Directory.GetCurrentDirectory()}\wwwroot\news.md"

      Donc à voir pour le développeur ce qu’il préfère comme lisibilité du code

  2. J’utilise File.ReadAllBytes(serverFileFullPath)
    serverFileFullPath contient par exemple: \\serverIP\… et Blazor me rajoute dans le nom /blazorapp/\\serverIP\…
    Savez-vous pourquoi ?

  3. Do you know how this will work with content from Razor Class Libraries?

    When they are published, the content gets moved to `wwwroot//` but this is not available in the debugger….

Leave a Reply