Filesystemwacther OnCreated to copy file to another folder

YUSOF 20 Reputation points
2023-08-23T08:04:03.6733333+00:00

Hi All,

How to copy all file from OnCreated to folder.

here is code to try;

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 Dot_Net

{

public partial class Form1 : Form

{

    private readonly string TargetPath = @"C:\Windows\test01";

    public Form1()

    {

        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)

    {

        var watcher = new FileSystemWatcher(@"c:\")

        {

            NotifyFilter = NotifyFilters.Attributes

                 | NotifyFilters.CreationTime

                 | NotifyFilters.DirectoryName

                 | NotifyFilters.FileName

                 | NotifyFilters.LastAccess

                 | NotifyFilters.LastWrite

                 | NotifyFilters.Security

                 | NotifyFilters.Size

        };

        watcher.Changed += OnChanged;

        watcher.Deleted += OnDeleted;

        watcher.Created += OnCreated;

        watcher.Renamed += OnRenamed;

        watcher.Error += OnError;

        watcher.Filter = "*.*";

        watcher.IncludeSubdirectories = true;

        watcher.EnableRaisingEvents = true;

        //this.Opacity = 0;

    }

    private static void OnChanged(object sender, FileSystemEventArgs e)

    {

        if (e.ChangeType != WatcherChangeTypes.Changed)

        {

            return;

        }

        Console.WriteLine($"Changed: {e.FullPath}");

    }

    private static void OnDeleted(object sender, FileSystemEventArgs e) => Console.WriteLine($"Deleted: {e.FullPath}");

    private void OnCreated(object source, FileSystemEventArgs e)

    {

        try

        {

            FileInfo fileInfo = new FileInfo(e.FullPath);

            string 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 + TargetFile)));

        }

        catch (Exception exception)

        {

            Debug.WriteLine(exception.Message);

        }

    }

    private void OnRenamed(object sender, RenamedEventArgs e)

    {

    }

    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)

        {

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

            Debug.WriteLine("Stacktrace:");

            Debug.WriteLine(ex.StackTrace);

            Debug.WriteLine("");

            DisplayException(ex.InnerException);

        }

    }

}

}

Thank

C#
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.
10,855 questions
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 44,516 Reputation points Microsoft Vendor
    2023-08-23T09:35:48.6433333+00:00

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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