I have a program that reads Excel file using ExcelDataReader.dll.
Everything was perfect until I moved the file reading to a new task:
Stream output = new MemoryStream();
httpRequest.Files[0].InputStream.CopyToAsync(output);
ImportDataWriter importDatawRiter = new ImportDataWriter(authenticationInfo);
Task.Run(() => importDatawRiter.ImportFile(output));
ImportLine Code:
public ImportResult ImportFile(Stream fs)
{
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
}
Now this line:
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
causes an Exception:
An exception of type 'System.IO.InvalidDataException' occurred in System.IO.Compression.dll but was not handled in user code
Message:
End of Central Directory record could not be found.
The Exception occurs from the second time I call the function.
What Can Be The Problem?
The problem is that you are not waiting for the Copy task to finish, so when you get to read the MemoryStream
, it is not full (it may even be completely empty), so, change your code to:
Stream output = new MemoryStream();
await httpRequest.Files[0].InputStream.CopyToAsync(output);
^^^^^
ImportDataWriter importDatawRiter = new ImportDataWriter(authenticationInfo);
Task.Run(() => importDatawRiter.ImportFile(output));
And, unless ImportFile
is a fire-and-forget action, I'd suggest you to use
await Task.Run(() => importDatawRiter.ImportFile(output));