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 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.
It is possible but you have to carefully control the file sharing you specify. Most .NET classes default to FileShare.Read, denying another process from writing to the file. But that cannot work if the file is opened by Excel, it already gained write access to it. You cannot deny a right that was already acquired.
To fix the problem, make your code look similar to this:
using (var fs = new FileStream(@"c:\\temp\\test.csv", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs)) {
// Read it...
}
Note the use of FileShare.ReadWrite. I verified this code works while Excel had test.csv opened.
Beware of the potential trouble you'll invite with this, odd things can happen when Excel writes to the file just as you are reading it. You'll likely read garbage, part of old data, part of new, without a good way to diagnose this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With