I am monitoring a folder for new files and need to process them. The problem is that occasionally file opening fails, because system has not finished copying it.
What is the correct way to test if the file is finished copying?
Clarification: I don't have write permissions to the folder/files and cannot control the copying process (it's the user).
You can find if some files have been copied or not. Right click on the folder or file you fear that might have been copied, go to properties, you will get information such as date and time of created, modified and accessed. The accessed one changes each time the file is opened or copied without opening.
Copy method takes three parameters. First the original file with full path, second the file to be copied file name with the new path and third parameter that is optional that is used to overwrite an existing file. If third parameter is true, the Copy method will overwrite if file already exists.
I think the only sure way to do this is by trying to open the file exclusively and catching a specific exception. I usually hate using exceptions for normal application logic, but I'm afraid for this scenario there's no other way (at least I haven't found one yet):
public bool FileIsDone(string path)
{
try
{
using (File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
{
}
}
catch(UnauthorizedAccessException)
{
return false;
}
return true;
}
Not sure about "the correct way", but you could use the monitoring tool (FileSystemWatcher
I guess) to fill an internal queue that you use for delayed processing. Or better yet: just use a queue to place files in that had the open fail, so you can retry them later.
If you are using FileSystemWatcher I don't think there's a robust solution to this problem. One approach would be try/catch/retry later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With