Hi @YUSOF , Welcome to Microsoft Q&A,
OnCreated gets the created file, constructs the target path in the specified directory, checks if a file with the same name exists in the target directory, deletes it if it exists, and then copies the newly created file to the target directory.
private void OnCreated(object source, FileSystemEventArgs e)
{
try
{
DirectoryInfo sourceDir = new DirectoryInfo(@"c:\"); // Change this to your source directory
FileInfo[] files = sourceDir.GetFiles();
foreach (FileInfo file in files)
{
string targetFile = Path.Combine(TargetPath, file.Name);
if (File.Exists(targetFile))
{
File.Delete(targetFile);
}
File.Copy(file.FullName, targetFile, true);
listBox1.Invoke((Action)(() => listBox1.Items.Add(file.FullName + " copied to " + targetFile)));
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.