Detect File Copy Completion in FileSystemWatcher

Ndebata
Posted by in C# category on for Intermediate level | Points: 250 | Views : 19753 red flag

Detect or Start a processing of a file only after it has copied to you system.

Introduction

Hello Everybody. Many of us might face the problem of detecting the File Copy completion in FileSystemWatcher. This article describes how to detect that file has been copied completely to our watch directory so that we can start processing the same.

Problem


Using FileSystemWatcher we can detect when a file has been created or deleted or changed etc by handling the respective events. Lets say we are copying a bigger file of 200MB from a network location, which may take several minutes. In this case FileSystemWatcher helps us to detect the creation, but we have no clue when it's copy has been completed.

Solution

   To detect whether copy has been completed or not what we can do, we will try to open the file at a regular interval. When we can successfully open it, we  can ensure that copy has been completed so go ahead and start processing the File. please take a look at the bellow code.

FileSystemWatcher watcher = new FileSystemWatcher(_watchfolder);

watcher.EnableRaisingEvents = true;

//watcher.Filter = ConfigurationManager.AppSettings["Watch_Filter"];

watcher.Created += new FileSystemEventHandler(file_Created);

In the watcher Created Event we can check whether file copy has been completed or not.

void file_Created(object sender, FileSystemEventArgs e)

{

   if(CheckFileHasCopied(e.FullPath))

   {

   //Start processing..

   }

}

The defination for the method CheckFileHasCopied is

private bool CheckFileHasCopied(string FilePath)

{

   try

   {

      if (File.Exists(FilePath))

      using (File.OpenRead(FilePath))

      {

         return true;

      }

      else

         return false;

   }

   catch (Exception)

   {

   Thread.Sleep(100);

      return CheckFileHasCopied(FilePath);

   }

}


Thanks,

Debata

Page copy protected against web site content infringement by Copyscape

About the Author

Ndebata
Full Name: Narayan Debata
Member Level: Starter
Member Status: Member
Member Since: 4/12/2011 6:43:18 AM
Country: India

http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Mistral on: 4/18/2011 | Points: 25

Unfortunately this does not tell you it has completed. It tell you it is not locked any more.

It is still impossible to tell if the file copy finished or has failed. This can result in a race on the file system where a copy has been cancelled. The "monitor" can then open it before the other cancelled process has had a chance to delete it.

Please use the tried and tested system for this where you copy the file so <filename>.tmp then rename it to the correct file .... which causes an atomic operation on the filesystem.

Login to post response

Comment using Facebook(Author doesn't get notification)