careers Reading server-side files using Blazor -
30 November 2020
Blazor server Read file

Reading server-side files using Blazor

tools
research
rss

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);
   }
}

 

privacy

2 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

Leave a Reply

research
rss
privacy