I am having trouble reading from an XLSX file (no trouble at all with XLS files) and I believe it has to do with the FileStream object. Here's my code:
string extention = Path.GetExtension(fileName);
using (FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
IExcelDataReader excelReader = null;
try
{
switch (extention.ToLower())
{
case ".xls":
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
break;
case ".xlsx":
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
break;
....
Again, when I read from an XLS file, it works, however for XLSX files, when I dig into the stream variable, I see the following
Handle = 'stream.Handle' threw an exception of type 'System.ObjectDisposedException'
Length = 'stream.Length' threw an exception of type 'System.ObjectDisposedException'
....
With the same exception for other members of FileStream. When I dig further into these exceptions, I see:
base {System.InvalidOperationException} = {"Cannot access a closed file."}
As the message. What does this mean? I'm assuming this is preventing me from reading from this file. Is there any way around this? Why would it work for XLS but not XLSX files?
Edit for Eric:
No dice. I'm getting a "Cannot Access a Closed Stream" exception on the MemoryStream object. I'm setting up the MemoryStream as follows (per [http://justtwoshare.blogspot.com/2010/04/how-to-convert-filestream-to.html](this site):
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
MemoryStream memStream = new MemoryStream();
memStream.SetLength(stream.Length);
stream.Read(memStream.GetBuffer(), 0, (int)stream.Length);
memStream.Flush();
Final Edit:
After having no luck with finding out what the issue with this was, I resorted to limiting the program to only accepting xls files...