I am building an application in C# in which I have to open a CSV file to read data from it. I get an exception when I try to open the CSV file from C# when that file is already open in Excel. The exception says that the process cannot access the file since it is already open. How can I solve this problem and open the file even if it is opened in other application?
Thanks,
Rakesh.
I faced this problem some time back.
You are missing the
FileShareparameter. 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.