How to Lock a file and avoid readings while it's writing

Posted by vtortola on Stack Overflow See other posts from Stack Overflow or by vtortola
Published on 2010-04-08T14:01:07Z Indexed on 2010/04/08 14:13 UTC
Read the original article Hit count: 714

My web application returns a file from the filesystem. These files are dynamic, so I have no way to know the names o how many of them will there be. When this file doesn't exist, the application creates it from the database. I want to avoid that two different threads recreate the same file at the same time, or that a thread try to return the file while other thread is creating it.

So I want to lock a file till its recreation is complete, if other thread try to access it ... it will have to wait the file be unlocked.

I've been reading about FileStream.Lock, but I have to know the file length and it won't prevent that other thread try to read the file, so it doesn't work for my particular case.

I've been reading also about FileAccess.None, but it will throw an exception (which exception type?) if other thread/process try to access the file... so I should develop a "try again while is faulting" ... and I don't like too much that approach, although maybe there is not a better way.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET