16

I want to read already open excel file with C#. I am using this method but it can't read the excel file while the file is open in Microsoft excel.

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read);

It gives IOException: The process cannot access the file 'myfile.xlsx' because it is being used by another process.

I hope you understands what I mean. I want to keep excel file open and while file is open at Microsoft excel i want to read it from C#. I am using C# net framework 4.0

Devendra D. Chavan
  • 8,871
  • 4
  • 31
  • 35
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342

6 Answers6

25

You need to open it with FileShare.ReadWrite:

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

See this answer.

Community
  • 1
  • 1
splintor
  • 9,924
  • 6
  • 74
  • 89
7

I think you can still copy the file while excel has it open, so you could make a copy of the file and then open that. Just make sure you clean up after yourself when you are done with the copy.

John Koerner
  • 37,428
  • 8
  • 84
  • 134
3

You could use the Interop library to use the already opened instance of Excel.

oExcel == (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
Koen
  • 2,501
  • 1
  • 32
  • 43
1

You can try the File.Open with a fourth parameter - fileShare.

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read, FileShare.Read);

You may need to specify write access also.

doobop
  • 4,465
  • 2
  • 28
  • 39
  • That's because you need to open it with FileShare.ReadWrite - see http://stackoverflow.com/questions/897796/how-do-i-open-an-already-opened-file-with-a-net-streamreader/898017#898017 – splintor Feb 20 '12 at 04:56
0

To open the same file more than once at the same time, it needs to be opened in shared mode.

Hope this may help others.

Farjad
  • 257
  • 4
  • 9
0

To ensure that correct opening and closing of the file please look at using the c# using statements

using (FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read)) 
{

}
Devendra D. Chavan
  • 8,871
  • 4
  • 31
  • 35
Somedeveloper
  • 817
  • 2
  • 14
  • 31
  • 1
    did you understand what i am asking ? i don't want to close excel and while file is open at microsoft office excel i want to read it to my C# – Furkan Gözükara Feb 14 '11 at 12:35