FileSystemWatcher – is File ready to use

When I ran into this problem, the best solution I came up with was to continually try to get an exclusive lock on the file; while the file is being written, the locking attempt will fail, essentially the method in this answer. Once the file isn’t being written to any more, the lock will succeed.

Unfortunately, the only way to do that is to wrap a try/catch around opening the file, which makes me cringe – having to use try/catch is always painful. There just doesn’t seem to be any way around that, though, so it’s what I ended up using.

Modifying the code in that answer does the trick, so I ended up using something like this:

private void WaitForFile(FileInfo file)
{
    FileStream stream = null;
    bool FileReady = false;
    while(!FileReady)
    {
        try
        {
            using(stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)) 
            { 
                FileReady = true; 
            }
        }
        catch (IOException)
        {
            //File isn't ready yet, so we need to keep on waiting until it is.
        }
        //We'll want to wait a bit between polls, if the file isn't ready.
        if(!FileReady) Thread.Sleep(1000);
    }
}

Leave a Comment