Unable to open a file using StreamReader - access exception

J

jkristia

StreamReader throws an exception if I attempt to open a .csv file which
is also opened by Excel.
I checked this list and found what I though was the solution, first
open the file stream in read only,
But unfortunately that doesn't work either

Stream s = File.OpenRead(filename);
using (StreamReader sr = new StreamReader(s))
{
}

File.OpenRead still throws the "can not access file" exception,
however I can open the file in Notepad at the same time as it is opened
in Excel.

Is this another bug in .NET, and is there any workaround ?

Thanks
Jesper
 
S

Sean Chambers

I havent looked anything up, but it sounds like excel opens a csv with
an exclusive file lock.

Try opening the file by passing in the filename into StreamReader
instead of opening a stream first from the file:

StreamReader sr = new StreamReader("file.csv");

Does that still throw an exception?

Hope this helps!

Sean
 
J

jkristia

StreamReader sr = new StreamReader("file.csv");

That was the first thing I did, but unfortunately that doesn't work
either, and that is the reason why I tried the other way.
The weird thing is that I can open the same csv file with notepad while
open in Excel with no problem.

Jesper
 
S

shriop

I found the question interesting, and couldn't figure it out myself,
which was a little crazy, but found the answer online, and it works,
but I couldn't explain to you why.

http://tinyurl.com/pw2xs

StreamReader reader = new StreamReader(new FileStream(@"file.csv",
FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
 
J

jkristia

yep - that works, thank you very much.

I think what does the trick is to set the share to ReadWrite instead of
Read.

Jesper
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top