Cannot READ a file being used by another process

  • Thread starter Thread starter Woody
  • Start date Start date
W

Woody

I try to open a file that is opened and used by win32service for
logging purposes in c#

The following code line
StreamReader sr = new StreamReader(filename);

gets an exception:

The process cannot access the file 'XX' because it is being used by
another process.

I can open the file using notepad or I can use C++ using the following
code:
FILE *f = fopen(filename, "r");

Can someone tell me what I'm doing wrong.

Thanks
 
The following code line
StreamReader sr = new StreamReader(filename);

gets an exception:

The process cannot access the file 'XX' because it is being used by
another process.

I can open the file using notepad or I can use C++ using the following
code:
FILE *f = fopen(filename, "r");

Can someone tell me what I'm doing wrong.

Instead of creating a StreamReader directly, have you tried to use the
overloaded version of File.Open() which takes a FileShare as a parameter,
specifying that you want to allow sharing read/write access to the file
(FileShare.ReadWrite)? Something like that:

FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite);
 
It Works!
I would like to know why it fails if I use
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read,
FileShare.Read)?

FileShare.Read instead of FileShare.Write

?
 
It Works!
I would like to know why it fails if I use
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read,
FileShare.Read)?

FileShare.Read instead of FileShare.Write

?

Whith FileShare.Read, you are allowing other processes to open the file to
read it but not to write it. Since the Windows Service you were talking
about in your first post has the file open to write it, you need to allow
read/write access sharing if you want to be able to open it or it will fail
because another process already has the file open for writing.
 
Try opening thru a file stream rather then direct opening with a filename...

FileStream file = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

StreamReader roseFile = new StreamReader(file);

**********************************************************************
Sent via Fuzzy Software @ http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
 
Back
Top