Home > Back-end >  How to display content of .txt file in Blazor WebAssembly
How to display content of .txt file in Blazor WebAssembly

Time:11-20

Like in topic. My question is - Is it possible and if yes, how to display content of .txt file in blazor app? I am using InputFile to load file from my computer. Below is my actual code which returns nothing.

<div class="col-4">
    <InputFile OnChange="OnInputFileChanged"></InputFile>
</div>

<p>
    @fileContent
</p>

@code{
    private string fileContent = "";

    private async void OnInputFileChanged(InputFileChangeEventArgs e)
    {
        var file = e.File;

        var buffer = new byte[file.Size];
        await file.OpenReadStream().ReadAsync(buffer);

        fileContent = $"{Convert.ToBase64String(buffer)}";
    }
}

CodePudding user response:

Here's a working version of your code:

@page "/"
<h3>ShowTextFile</h3>
<div class="col-4">
    <InputFile OnChange="OnInputFileChanged"></InputFile>
</div>

<pre>
    @fileContent
</pre>

@code{
    private string fileContent = "";

    private async Task OnInputFileChanged(InputFileChangeEventArgs e)
    {
        var file = e.File;
        long maxsize = 512000;

        var buffer = new byte[file.Size];
        await file.OpenReadStream(maxsize).ReadAsync(buffer);
        fileContent = System.Text.Encoding.UTF8.GetString(buffer);
    }
}
  • Related