I am trying to write a program that watches over a folder and when any file in the folder gets changed/updated, it has to copy that file to another folder. In particular I want to use this program to copy dll files. Whenever I build a project using VS, the dll gets created, then I want my program to copy the newly generated dll to another folder.
The problem is that when I try to copy the file, I get an exception saying that The process cannot access the file because it is being used by another process. I know what this exception means and I've seen answers on SO on how to fix it (but in most cases the answers assume that the dev has control over the other process also). In my case I have no control over the other process that is using that file (probably VS ?).
Is it even possible to achieve this? If not then why am I able to manually copy that dll to another folder but cannot do it programmatically. Here's the code I use to copy the file.
private void CopyFile(object sender, FileSystemEventArgs e)
{
string fileName = e.FullPath;
try
{
System.Threading.Thread.Sleep(5000);
File.Copy(fileName, System.IO.Path.Combine(DestinationFolderPath, fileName), true);
this.Dispatcher.Invoke(() =>
{
Log.Text += "Copied " + e.Name + Environment.NewLine;
});
}
catch (IOException exception)
{
this.Dispatcher.Invoke(() =>
{
Log.Text += "Error copying file " + e.Name + " " + exception.Message + Environment.NewLine;
});
}
}