I'm creating a file in a dll with:

invoke CreateFile, addr logfile, GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, 0, CREATE_ALWAYS, 0, 0

and then trying to open it for read access with:

(c# code)
fs = new FileStream("whlog.log", FileMode.Open, FileAccess.Read, FileShare.Read);

which always gives me:

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file "C:\\whlog.log" because it is being used by another process.

What gives?
Posted on 2003-08-25 16:00:53 by grv575
That's because you first tell the system to create with a write access (GENERIC_READ or GENERIC_WRITE), and then in your C# code you tell the system to open the file in read-only share mode. Th system cannot deny write to other processes on that file, because the file is already opened for writing, so an error is generated. You should use a FileShare.Read or FileShare.Write in your C# code.
Posted on 2003-08-25 17:50:43 by Morris
Dude you rock! :cool:

Looks like this works as intended:

invoke CreateFile, addr logfile, GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, 0, CREATE_ALWAYS, 0, 0
---
fs = new FileStream("whlog.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

Guess it has to do with the specifics of the windows file locking mechanism. Odd that it can't grant writing privledges to just the first process since this is a common idiom (one writer, many readers).
Posted on 2003-08-27 01:35:50 by grv575
Never mind. Looks that like can be accomplished with:

invoke CreateFile, addr logfile, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0
---
fs = new FileStream("whlog.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

Using ReadWrite access does generate an execption as intended. So I guess this would be the proper code to use in this case. (Even though it seems odd to only use a fs_read flag in the first call and requiring a fs_readwrite flag in the second since it really isn't shared for writing...a third fileopen call for read & write access will fail).

I guess they do document it even if it isn't very intuitive:
"If the object has already been opened with write access, the sharing mode must include this flag."
Posted on 2003-08-27 01:43:37 by grv575