Search code examples
c#.netfilefilestreamfilesystemwatcher

Is there any way to check file readability before trying to read it in FileSystemWatcher.Changed event?


I use FileSystemWatcher to monitor some folder for changes. When it fires file changed event, I need to read that file and update some stuff. The problem is that when this event is fired, target file is still forbidden to read even in this way FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

Is there any other events notifying that file ended change? Or anyway to create some waiter that will wait for file read ability via some standard ways (WinAPI or etc). Or maybe looping try catch is the only choice?


Solution

  • You should use the below helper method to return the filestream if it is available.

    public static FileStream WaitForFile(string fullName)
    {
        FileStream fs = null;
        int numTries = 0;
        while (true)
        {
            ++numTries;
            try
            {
                //try to open the file
                fs = new FileStream(fullName, FileMode.Open, FileAccess.Read, FileShare.None, 100);
    
                fs.ReadByte();//if it's open, you can read it
                fs.Seek(0, SeekOrigin.Begin);//Since you read one byte, you should move the cursor position to the begining.                    
                break;
            }
            catch (Exception ex)
            {
                if (numTries > 10)//try 10 times
                {
                    return fs;//Or you can throw exception
                }
                System.Threading.Thread.Sleep(10000);//wait 
            }
        }
        return fs;
    }