How to do.Everytime to save the file need to move in string TargetPath = @"C:\Users\sy\Documents\test22" then if name of the file are same , file in string TargetPath = @"C:\Users\sy\Documents\test22" need to delete and paste to

MIPAKTEH_1 545 Reputation points
2024-12-31T11:15:16.39+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;

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

        }

    }

}

}

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,215 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 119.2K Reputation points
    2024-12-31T11:35:17.2466667+00:00

    Try to remove the System.IO.File.Delete(targetFile) and add an argument to Move:

    System.IO.File.Move(e.FullPath, targetFile, true).


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.