Try to delete all file coming with filesystemwacther and delete all file created by user.

MIPAKTEH_1 365 Reputation points
2024-09-28T14:35:40.1233333+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;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Chk_delete
{
    public partial class Form1 : Form
    {
        static readonly string rootFolder = @"C:\*.*";
        string authorsFile = "*.*";

        FileSystemWatcher watcher = new FileSystemWatcher(@"C:\");
        private readonly string TargetPath = @"C:\Users\sy\Documents\test22";
        private bool IsNewFile = false;

        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.Filter = "*.*";
            watcher.Created += OnCreated;
            watcher.Renamed += OnRenamed;
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;

        }
        private string newFilePath;
        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            newFilePath = e.FullPath;
            IsNewFile = true;
        }

        private void OnRenamed(object sender, RenamedEventArgs e)
        {

            if (IsNewFile && e.OldFullPath == newFilePath)
                try
            {
                    FileInfo fileInfo = new FileInfo(e.FullPath);
                    var targetFile = Path.Combine(TargetPath, fileInfo.Name);
                    File.Copy(e.FullPath, targetFile, true);
                    listBox1.Invoke((Action)(() => listBox1.Items.Add(e.FullPath + " copied to " + targetFile)));

                    File.Delete(targetFile);

                    if (File.Exists(Path.Combine(rootFolder, authorsFile)))
                    {
                        // If file found, delete it
                        File.Delete(Path.Combine(rootFolder, authorsFile));
                        Console.WriteLine("File deleted.");
                    }
                    else Console.WriteLine("File not found");
                }
                catch (Exception exception)
                {
                Debug.WriteLine(exception.Message);
                }

        }

        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);
        }

    }
}

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.
11,002 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 46,296 Reputation points Microsoft Vendor
    2024-10-01T02:23:48.0533333+00:00

    Hi @MIPAKTEH_1 , Welcome to Microsoft Q&A,

    You can try the following code.

    • Use FileSystemWatcher to detect file creation and rename events.
    • Delete files immediately after detection.
    • Handle file locks or exceptions during deletion.
    • Ensure that both OnCreated and OnRenamed events result in file deletion.
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Windows.Forms;
    namespace Chk_delete
    {
        public partial class Form1 : Form
        {
            static readonly string rootFolder = @"C:\Users\sy\Documents\test22";  // Replace with actual folder to monitor
            FileSystemWatcher watcher;
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                // Initialize FileSystemWatcher
                watcher = new FileSystemWatcher(rootFolder)
                {
                    NotifyFilter = NotifyFilters.Attributes
                        | NotifyFilters.CreationTime
                        | NotifyFilters.DirectoryName
                        | NotifyFilters.FileName
                        | NotifyFilters.LastWrite
                        | NotifyFilters.Size,
                    Filter = "*.*",  // Monitor all file types
                    IncludeSubdirectories = true,
                    EnableRaisingEvents = true
                };
                // Hook into events
                watcher.Created += OnCreated;
                watcher.Renamed += OnRenamed;
            }
            // Handle newly created files
            private void OnCreated(object sender, FileSystemEventArgs e)
            {
                try
                {
                    // Delete file after it's created
                    DeleteFile(e.FullPath);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error while deleting created file: {ex.Message}");
                }
            }
            // Handle renamed files
            private void OnRenamed(object sender, RenamedEventArgs e)
            {
                try
                {
                    // Delete renamed file
                    DeleteFile(e.FullPath);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error while deleting renamed file: {ex.Message}");
                }
            }
            // Method to delete a file safely
            private void DeleteFile(string filePath)
            {
                if (File.Exists(filePath))
                {
                    try
                    {
                        // Log file deletion
                        listBox1.Invoke((Action)(() => listBox1.Items.Add($"Deleting file: {filePath}")));
                        // Delete the file
                        File.Delete(filePath);
                        // Log success
                        listBox1.Invoke((Action)(() => listBox1.Items.Add($"File deleted: {filePath}")));
                    }
                    catch (IOException ioEx)
                    {
                        Debug.WriteLine($"IOException: {ioEx.Message} - File may be in use.");
                    }
                    catch (UnauthorizedAccessException unAuthEx)
                    {
                        Debug.WriteLine($"UnauthorizedAccessException: {unAuthEx.Message} - Check permissions.");
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"Error while deleting file: {ex.Message}");
                    }
                }
                else
                {
                    Debug.WriteLine($"File not found: {filePath}");
                }
            }
            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);
            }
        }
    }
    
    

    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.


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.