0

I am accessing an excel file C# and reading data from it. Here is the code that have written so far.

string fileName = @"C:\repos\somepath\Workbook.xlsx";
string sheetName = "Sheet1";
        FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);

IExcelDataReader excelReader = 
ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
DataTableCollection table = result.Tables;
DataTable resultTable = table[sheetName];
return resultTable;

My issue is as soon as I run my code, if the file is open, it throws an exception. After that I need to close the excel manually and then run again my code.

Is there a way which I can handle this and tell the code itself to save the changes and close it [may be the process] and then once the file is close proceed to the next step?

Any suggestions would be of great help.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • 1
    https://stackoverflow.com/questions/8875120/save-an-excel-file-in-c-sharp – Samvel Petrosov Jul 19 '17 at 08:21
  • 1
    You are using a proprietary library, that only reads Excel files. I suggest to use interop or create the XLSX yourself – Romano Zumbé Jul 19 '17 at 08:22
  • @SamvelPetrosov this question isn't helpful at all - `xls` was abandoned 10 years ago. *Interop* requires an Excel installation and just can't be used on servers or standalone applications. Everyone uses either the Open XML SDK or libraries like EPPLus – Panagiotis Kanavos Jul 19 '17 at 08:39
  • What exception? Where? If `File.Open` throws why do you mention Excel at all? Either close the file or try to open it with share read access. Why *is* the file opoen? Did you forget to close it? The code you posted is guaranteed to cause such problems – Panagiotis Kanavos Jul 19 '17 at 08:41
  • The duplicate shows how to read from a file that's already in use. You may not have to do that though, if the file is open simply because the code didn't close it. You should use `using(var stream = File.Open()...)){ /* rest of the code */; return resultTable;}` to ensure the stream is closed when it's no longer needed – Panagiotis Kanavos Jul 19 '17 at 08:48
  • no, I want the file to be closed physically, which means close it from the process itself – Bishwaroop Chakraborty Jul 19 '17 at 08:56

0 Answers0