2

Using Blazor wasm app (NET standard 2.1) and the BlazorFileReader in the following code snippet (shortened, in my app it is divided into a .razor file and a .razor.cs file but shortened and put together here for the sake of simplicity):

@inject Blazor.FileReader.IFileReaderService fileReaderService
@using Blazor.FileReader;
    <div class="ml-2">
        <input type="file" @ref="InputElement" @onchange="FilesSelected" multiple accept=".txt,.csv" />
    </div>

@code {
        ElementReference InputElement;
        [Parameter] public List<string> FileContent { get; set; }
        async Task FilesSelected()
        {
            foreach (var file in await fileReaderService.CreateReference(InputElement).EnumerateFilesAsync())
            {
                using (Stream stream = await file.OpenReadAsync())
                {
                    FileContent = await ReadLinesAsync(stream, Encoding.UTF8);
                }
            }
        }
        public async Task<List<string>> ReadLinesAsync(Stream stream, Encoding encoding)
        {
            using (var reader = new StreamReader(stream, encoding))
            {
                string line;
                var result = new List<string>();
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    result.Add(line);
                }
                return result;
            }
        }
}

Running this code in debug mode (Visual studio 2019 v 16.6 preview) reads any text file just fine. But when running in release mode the StreamReader.ReadLineAsync() returns empty strings.

Does anyone know why ReadLineAsync() does this? I have looked at this...

Erik Thysell
  • 1,160
  • 1
  • 14
  • 31

1 Answers1

2

This is a bug in the current implementation of Blazor.

Until it is resolved, here is a workaround (the code is more or less equivalent... but works!):

    public async Task<List<string>> ReadLinesAsync(Stream stream, Encoding encoding)
    {
        using (var reader = new StreamReader(stream, encoding))
        {

            var result = new List<string>();
            string line = await reader.ReadLineAsync();
            while (line != null)
            {
                result.Add(line);
                line = await reader.ReadLineAsync();
            }
            return result;
        }
    }

Edit: The bug seems to be in the Optimizer. Turning off "Optimize" (on by default when compiling in Release) is an alternative workaround.

Tewr
  • 3,713
  • 1
  • 29
  • 43