C# - File.MoveTo Does not work - Cannot create a file when that file already exists. - C Sharp

Scenario: Download Script

You are working as C# developer and you need to write a program that should move all the files from a folder to another folder. You wrote the code and used file.MoveTo, it moved the files first. Later when you try to move the next batch, it failed with error "Cannot create a file when that file already exists.".

That means file already exists in the destination folder, you need to modify your script. We can delete the file if already exists and then move the file to destination folder.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            //Provider Source Folder Path
            string SourceFolder = @"C:\Source\";
            //Provide Destination Folder path
            string DestinationFolder = @"C:\Destination\";
            
           var files = new DirectoryInfo(SourceFolder).GetFiles("*.*");
      
            //Loop throught files and Move to destination folder
          foreach (FileInfo file in files)
            {
                //delete file if already exists
                File.Delete(DestinationFolder + file.Name);
                
                //Move the file to destination folder
              file.MoveTo(DestinationFolder+file.Name);

            }

        }
    }
}

No comments:

Post a Comment