I was trying to detect a file in a folder using Filewatcher and move the file to a new location. While doing so using a console application, I am getting error as The process cannot access the file because it is being used by another process
.
I am getting this error at File.Move(f.FullName, System.IO.Path.Combine(@"C:\Users\ADMIN\Downloads\FW_Dest", Path.GetFileName(f.FullName)));
in the OnChanged
method.
Please check the below code and help me with this issue. Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.Permissions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\ADMIN\Downloads\FW_Source";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
DirectoryInfo directory = new DirectoryInfo(@"C:\Users\ADMIN\Downloads\FW_Source\");
FileInfo[] files = directory.GetFiles("*.*");
foreach (var f in files)
{
File.Move(f.FullName, System.IO.Path.Combine(@"C:\Users\ADMIN\Downloads\FW_Dest", Path.GetFileName(f.FullName)));
}
}
}
}