IsFileReady

suggest change

A common mistake with FileSystemWatcher is to handle the event as soon as the file is created. The event can run before the writer has finished.

For example, another program may be copying a 1 GB file. The created event runs at the start of that copy, so you need to wait until the file is ready.

This method checks whether the file can be opened with exclusive access. It returns false for an empty file, so a finished empty file never looks ready. Any failure, including a missing file or access denied, also returns false.

public static bool IsFileReady(String sFilename)
{
    // If the file can be opened for exclusive access it means that the file
    // is no longer locked by another process.
    try
    {
        using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if (inputStream.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }
    catch (Exception)
    {
        return false;
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents