Trying to figure out why I am unable to read a MemoryStream using ExcelDataReader. If I hard code the path to the CSV file and pass the stream as a FileStream it works. My problem is that I am getting the file from Blazor using <InputFile OnChange="LoadFile" accept=".csv,.xlsx,.xls" /> which only provides me an IBrowserFile, which gives me a Stream, not a FileStream. When I attempt to pass this in the following code (which works on this file if I pass a FileStream) I get an "Invalid Signature" exception.
The code:
using (var memoryStream = new MemoryStream()){ System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); // Copy the file data to the memory stream await browserFile.OpenReadStream().CopyToAsync(memoryStream); memoryStream.Position = 0; // Reset stream position to the beginning var config = new ExcelReaderConfiguration { FallbackEncoding = System.Text.Encoding.UTF8 // Default encoding }; // Exception happens here, CreateReader... using var reader = ExcelReaderFactory.CreateReader(memoryStream, config); var result = reader.AsDataSet(new ExcelDataSetConfiguration() { ConfigureDataTable = _ => new ExcelDataTableConfiguration() { UseHeaderRow = true // Use the first row as column names } });}The body of the exception is:
ExcelDataReader.Exceptions.HeaderException HResult=0x80131500 Message=Invalid file signature. Source=ExcelDataReader StackTrace: at ExcelDataReader.ExcelReaderFactory.CreateReader(Stream fileStream, ExcelReaderConfiguration configuration) at CollectXScore.Web.Utilities.ExcelCSVFileReader.<LoadFile>d__1.MoveNext() in mycode.cs:line 44 This exception was originally thrown at this call stack: [External Code]When make the call this way it works for the same file:
FileStream source = File.Open("C:\\myfilepath\\" + browserFile.Name, FileMode.Open);using var reader = ExcelReaderFactory.CreateReader(source);What am I doing wrong?