Furkan Gözükara
Furkan Gözükara

Reputation: 23810

How to read open excel file at C#

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

Upvotes: 16

Views: 19762

Answers (6)

Farjad
Farjad

Reputation: 257

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.

Upvotes: 0

splintor
splintor

Reputation: 10154

You need to open it with FileShare.ReadWrite:

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

See this answer.

Upvotes: 26

John Koerner
John Koerner

Reputation: 38077

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.

Upvotes: 7

Koen
Koen

Reputation: 2571

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

oExcel == (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")

Upvotes: 3

Somedeveloper
Somedeveloper

Reputation: 867

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)) 
{

}

Upvotes: 0

doobop
doobop

Reputation: 4510

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.

Upvotes: 1

Related Questions