Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a file is fully copied in .NET

Tags:

.net

file

copy

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).

like image 884
Viesturs Avatar asked Jul 20 '09 07:07

Viesturs


People also ask

How do you know if a file is fully copied?

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.

Does file copy overwrite C#?

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.


3 Answers

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;
}
like image 91
Philippe Leybaert Avatar answered Oct 22 '22 05:10

Philippe Leybaert


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.

like image 37
peSHIr Avatar answered Oct 22 '22 04:10

peSHIr


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.

like image 38
Darin Dimitrov Avatar answered Oct 22 '22 04:10

Darin Dimitrov