how to through and catch the response while already existed files alert when moving the files through source to destination in C# RRS feed

  • Question

  • User592448885 posted

    I have a source and destination path with the same folder and file names (source has some extra files). my question is when I have cut source locations files and folders and to paste the destination location

    1. how to paste initially the extra files(destination not having files)?
    2. how to through the error after paste the extra files "the folder and files already exist do you want to replace it" message?
    3. after getting the response how can I move and delete the source files?

    somebody can help me guys I am stuck with this logic nearly 2 days.

    Note: am the beginner of the C# and server-side code.

    thanks, advance.

    Wednesday, October 10, 2018 4:23 AM

All replies

  • User-821857111 posted

    The error message dialog is only relevant if you are working on the desktop. If you want to copy files from place A to place B that don't already exist in place B, you just need to use the File.Exists method to check if they are there already or not.:

    var source = <your source path>";
    var destination = <your destination path>;
    foreach(var file in Directory.GetFiles(source))
        if(!File.Exists(Path.Combine(destination, Path.GetFileName(file))))
            File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));

    Wednesday, October 10, 2018 6:37 AM
  • User592448885 posted

    Hi Mike,

    thanks for your reply,

    I have already processed this case with using Exist method but I need to handle the replace case while paste the files place A to B? 

    is there any other option available then please suggest me. and now I am handled my case with delete case.

                         if (fileExist)
    File.Move(oldPath, newPath);

    Wednesday, October 10, 2018 7:17 AM
  • User1724605321 posted

    Hi suresh ,

    You can also use the File.Replace Method , which is used to replace the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file :


    But if the destination file is missing , File.Replace will throw error but  File.Delete, File.Move won't.

    Best Regards,

    Nan Yu

    Thursday, October 11, 2018 3:16 AM