File open fails if the file is being used by another process

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I'm trying to open a file with read access only, e.g. FileStream fs = new
FileStream("C:\foo.txt", FileMode.Open, FileAccess.Read); The file is open
by another process and the FileStream constructor throws an IOException. I
thought that it was possible to open a file with read access even if it's
being used by another process. Is that not true?

Thanks,
Otik
 
I believe the other process is a C++ app, but I don't know how it specified
file sharing. However, I can open the file with Notepad and other apps
(while the other process is using it), so I don't think it's denying read
access. Any ideas why I can't open it for reading using my .NET app?
 
use
FileStream fs = new FileStream("C:\foo.txt", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);

That may work for you. The point of using FileShare is that you want to
share the read/write permission with anyone else who needs the file. (It's
counterintuitive, I know).

If the other app didn't lock the file, you should be able to read from it.
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
Nick,

Thanks for the response. Specifying FileShare.ReadWrite worked! I had
tried just FileShare.Read since I only wanted read access, but I guess you
need to specify write as well since the other process is writing to the file.

Thanks,
Otik
 
Back
Top