1

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?

exception screenshot

4
  • are you using this on an XLS file, instead of XLSX? Commented Jan 25, 2018 at 13:12
  • @Ctznkane525 no. I use first and second time exactly the same file. both times xlsx. Commented Jan 25, 2018 at 13:13
  • 1
    You aren't awaiting .CopyToAsync(output);. So the code goes when the copy hasn't finished Commented Jan 25, 2018 at 13:13
  • @CamiloTerevinto That was the problem. Please Insert your Comment as Answer, I will mark it as the correct answer. Commented Jan 25, 2018 at 13:26

1 Answer 1

3

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)); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.