简体   繁体   中英

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?

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;
}

Unfornately there's no guarantee that you can access the file when Changed event raised. Here'is a topic whic may interest you in how to wait for the file to be available for Open.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM