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