Hi @MIPAKTEH_1 , Welcome to Microsoft Q&A,
Don't check if the file exists in the OnCreated event handler and delete it manually. This is because FileSystemWatcher triggers the OnCreated event whenever a new file is created, including creating a new file by copying or moving an existing file
The third parameter true of File.Copy indicates that the target file will be overwritten, and you do not need to manually determine whether it exists. Just delete the judgment code directly.
The oncreated event can be simplified to:
private void OnCreated(object sender, FileSystemEventArgs e)
{
try
{
var targetFile = Path.Combine(TargetPath, Path.GetFileName(e.FullPath));
File.Copy(e.FullPath, targetFile, true);
listBox1.Invoke((Action)(() => listBox1.Items.Add(e.FullPath + " 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.