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
andOnRenamed
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.