c# - File sharing not working as expected -


i have file sharing issue process trying read log file whilst still open nlog. in diagnosing issue, found surprising. following fails:

using (var filestream1 = new filestream("test.file", filemode.append, fileaccess.write, fileshare.read)) using (var filestream2 = new filestream("test.file", filemode.open, fileaccess.read, fileshare.read)) { } 

the second filestream constructor call fails with:

system.io.ioexception unhandled   message=the process cannot access file 'c:\...\test.file' because being used process.   source=mscorlib   stacktrace:        @ system.io.__error.winioerror(int32 errorcode, string maybefullpath)        @ system.io.filestream.init(string path, filemode mode, fileaccess access, int32 rights, boolean userights, fileshare share, int32 buffersize, fileoptions options, security_attributes secattrs, string msgpath, boolean bfromproxy, boolean uselongpath)        @ system.io.filestream..ctor(string path, filemode mode, fileaccess access, fileshare share) 

this despite fact first filestream indicates willingness share reading. found more surprising works:

using (var filestream1 = new filestream("test.file", filemode.append, fileaccess.write, fileshare.read)) using (var filestream2 = new filestream("test.file", filemode.open, fileaccess.read, fileshare.readwrite)) { } 

um, yes, requesting more access when opening second stream bypasses issue. baffled why case, , can assume misunderstanding something. i've read through api docs support current mental model how should work, contrary how work.

here supporting quotes docs:

a typical use of enumeration define whether 2 processes can simultaneously read same file. example, if file opened , read specified, other users can open file reading not writing.

here's gem:

the following filestream constructor opens existing file , grants read-only access other users (read).

filestream s2 = new filestream(name, filemode.open, fileaccess.read, fileshare.read);

can shed light on behavior. i'm testing on .net 4 % windows xp.

 var filestream2 = new filestream(..., fileshare.read) 

this trips lots of programmers. assumes added read sharing. didn't, original file access request allowed reading , specifying again doesn't change anything. instead denies write sharing. , cannot work because got write access. , using it, cannot remove right. request access file fail.

you must include fileshare.write.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -