Try to remove the System.IO.File.Delete(targetFile) and add an argument to Move:
System.IO.File.Move(e.FullPath, targetFile, true)
.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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;
using static System.Net.WebRequestMethods;
namespace Let_C
{
public partial class Form1 : Form
{
private const string TargetPath = @"C:\Users\sy\Documents\test22";
//static readonly string TargetPath = @"C:\Data_";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FileSystemWatcher watcher = new FileSystemWatcher(@"c:\\")
{
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;
}
public static async Task<bool> IsFileReadyAsync(string filePath)
{
int retries = 25;
while (retries-- > 0)
{
try
{
using (FileStream stream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
return true; // File is ready
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
await Task.Delay(5000); // Delay before retry
}
return false;
}
private async void OnCreated(object source, FileSystemEventArgs e)
{
try
{
string targetFile = Path.Combine(TargetPath, Path.GetFileName(e.FullPath));
if (await IsFileReadyAsync(e.FullPath))
{
System.IO.File.Move(e.FullPath, targetFile);
if (System.IO.File.Exists(targetFile))
{
try
{
System.IO.File.Delete(targetFile);
}
catch (Exception ex)
{
DisplayException(ex);
}
}
// Update the UI safely
listBox1.Invoke((Action)(() =>
listBox1.Items.Add($"Copied: {e.FullPath} to {targetFile}")));
}
else
{
Debug.WriteLine($"File not ready: {e.FullPath}");
}
}
catch (Exception ex)
{
DisplayException(ex);
}
}
private static void DisplayException(Exception ex)
{
if (ex != null)
{
Debug.WriteLine($"Message: {ex.Message}");
Debug.WriteLine("Stack trace:");
Debug.WriteLine(ex.StackTrace);
Debug.WriteLine("");
DisplayException(ex.InnerException);
}
}
}
}
Try to remove the System.IO.File.Delete(targetFile) and add an argument to Move:
System.IO.File.Move(e.FullPath, targetFile, true)
.