Exception in opening a file that is already open

I faced this problem some time back.

You are missing the FileShare parameter. Without specifying that, if you open a file, it will be locked exclusively by your application. But since it’s already been opened by Excel (or any other app), you will receive an exception.

You can try using this – I think this will be your best bet –

using (FileStream fs = File.Open(<file-path>, FileMode.Open, FileAccess.Read, FileShare.Read))

This code says: Hello Excel! If you may permit (read, not throw exception), I would like to read the file, though I will not try to own it and I know that you may modify it anytime.

If this throws error, then Excel has denied you even the read access. Too bad then!
All the best.

Leave a Comment