Search code examples
c#filesystemwatcher

An file reading error occurred while handling FileSystemWatcher.Created event


files was uploaded via FTP,it thows a IO Exception that file was occupied

var watcher = new FileSystemWatcher();
watcher.Created += (sender, e) =>
{
    var lines = File.ReadAllLines(e.FullPath, Encoding.UTF8); //io exception here
};

waiting for your answer,thanks a lot.


Solution

  • You can use while and try-catch block. Put your file-reading code in while loop and loop until you successfully read file (it means that you passed try block successfully). Or use some delay, like suggested in comments (but this doesn't guarantee, that exception won't occur).

    You will exit on two occasions: file successfully read or exception other than IO is thrown. It means you need more sophisticated catch part. You can go more into details with this :)