How do I read static or local files in Blazor WebAssembly?

Platform: Blazor| Category : Web API, General

You can read static files by creating HttpClient Get calls. The GetStringAsync method sends a request to the specific URI and returns the response body as a string in an async operation. 

@inject HttpClient Http

@code {

    protected override async Task OnInitializedAsync()
    {
        var content = await Http.GetStringAsync(request Uri);

    }
}

If you can read local file, you will use ReadAsync() and  Encoding.UTF8.GetString() methods. Here is an example:

@page "/read localfile" 
<InputFile OnChange="@HandleFileSelection" /> 
<button @onclick="ReadFile">Read File</button> 
@if (!string.IsNullOrEmpty(fileContent)) 
{ 
    <div>@fileContent</div> 
} 

@code { 
    private IBrowserFile? file; 
    private string? fileContent; 
    private void HandleFileSelection(InputFileChangeEventArgs e) 
    { 
        file = e.File; 
    } 
    private async Task ReadFile() 
    { 
        if (file != null) 
        { 
            var stream = file.OpenReadStream(); 
            var buffer = new byte[file.Size]; 
            await stream.ReadAsync(buffer, 0, (int)file.Size); 
            fileContent = System.Text.Encoding.UTF8.GetString(buffer); 
        } 
    } 
} 

Note: The project mentioned above is designed for reading local text format documents. 

View Sample in GitHub  

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.