Home All Groups Group Topic Archive Search About

Cannot READ a file being used by another process

Author
27 Oct 2005 2:48 PM
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

Author
27 Oct 2005 3:48 PM
Mehdi
On 27 Oct 2005 07:48:23 -0700, Woody wrote:

> 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);
Author
27 Oct 2005 5:01 PM
Woody
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

?
Author
27 Oct 2005 5:36 PM
Mehdi
On 27 Oct 2005 10:01:40 -0700, Woody wrote:

> 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.
Author
28 Oct 2005 8:10 AM
Woody
Now it works and I also understand why.
Thanks a lot!
Author
2 Nov 2005 2:28 PM
jeff.reimann@softhome.net
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...

AddThis Social Bookmark Button