[Mono-list] File Locking

Edward Ned Harvey (mono) edward.harvey.mono at clevertrove.com
Wed Feb 17 14:45:59 UTC 2016


> From: mono-list-bounces at lists.ximian.com [mailto:mono-list-
> bounces at lists.ximian.com] On Behalf Of shrimpywu
> 
> i have the same issue. any solution?

Kinda sorta. The underlying issue is that OSX, Linux, and Windows all have different underlying file locking constructs, and then of course, there's some variability about even *which* filesystem is being used. I didn't thoroughly figure out all the answers for every OS or filesystem, and I don't know under which situations this will be good enough, but this is what I ended up using, works under the conditions we needed it to work:

using (var foo = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {     // must include Write access in order to lock file
	foo.Lock(0, 0);   // 0,0 has special meaning to lock entire file regardless of length
}

For windows, simply specifying the FileAccess and FileShare is good enough. For linux, at least ext4, files are concurrently readable regardless of what you specify for FileAccess and FileShare. The Lock() method does something of a soft-lock. It's not enforced by the OS, but at least all the situations we tried, other client apps honor the lock. Didn't look into it any deeper.


More information about the Mono-list mailing list