Something wrong when put "Delete " in Filesystemwatcher .Code cannot copy to destination target.

MIPAKTEH_1 605 Reputation points
2023-10-21T10:51:29.4066667+00:00
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.Drawing;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace WMI_5

{

public partial class Form1 : Form

{

    private readonly string TargetPath = @"C:\Users\User\Documents\test\";

    FileSystemWatcher watcher = new FileSystemWatcher();

    public Form1()

    {

        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)

    {

        watcher.NotifyFilter = NotifyFilters.Attributes

     | NotifyFilters.CreationTime

     | NotifyFilters.DirectoryName

     | NotifyFilters.FileName

     | NotifyFilters.LastAccess

     | NotifyFilters.LastWrite

     | NotifyFilters.Security

     | NotifyFilters.Size;

        watcher.Path = @"c:\";

        watcher.Filter = "*.*";

        watcher.Created += OnCreated;

        watcher.Error += OnError;

        watcher.EnableRaisingEvents = true;

        watcher.IncludeSubdirectories = true;

    }

    private void OnCreated(object sender, FileSystemEventArgs e)

    {

        try

        {

            FileInfo fileInfo = new FileInfo(e.FullPath);

            var targetFile = Path.Combine(TargetPath, fileInfo.Name);

            if (File.Exists(targetFile))

            {

                File.Delete(targetFile);

            }

            File.Copy(e.FullPath, targetFile, true);

            listBox1.Invoke((Action)(() => listBox1.Items.Add(e.FullPath + " copied to " + targetFile)));

        }

        catch (Exception exception)

        {

            Debug.WriteLine(exception.Message);

        }

    }

    private static void OnError(object sender, ErrorEventArgs e) => DisplayException(e.GetException());

    /// <summary>

    /// For debug purposes

    /// For a production environment write to a log file

    /// </summary>

    /// <param name="ex"></param>

    private static void DisplayException(Exception ex)

    {

        if (ex == null) return;

        Debug.WriteLine($"Message: {ex.Message}");

        Debug.WriteLine("Stacktrace:");

        Debug.WriteLine(ex.StackTrace);

        Debug.WriteLine("");

        DisplayException(ex.InnerException);

    }

}
}

we need remove this line;

                if (File.Exists(targetFile))
                {
                    File.Delete(targetFile);
                }

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Anonymous
    2023-10-23T02:31:56.18+00:00

    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.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.