Cannot create a file when that file already exists when using Directory.Move

后端 未结 5 923
我寻月下人不归
我寻月下人不归 2020-12-17 08:59

I am trying to move the directory from one location to another location on the same drive. I am getting \"Cannot create a file when that file already exists

5条回答
  •  Happy的楠姐
    2020-12-17 09:37

    As both of the previous answers pointed out, the destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.

    Something like this:

    class Program
    {
        static void Main(string[] args)
        {
            string sourcedirectory = @"C:\source";
            string destinationdirectory = @"C:\destination";
            string backupdirectory = @"C:\Backup";
            try
            {
                if (Directory.Exists(sourcedirectory))
                {
                    if (Directory.Exists(destinationdirectory))
                    {
                        //Directory.Delete(destinationdirectory);
                        Directory.Move(destinationdirectory, backupdirectory + DateTime.Now.ToString("_MMMdd_yyyy_HHmmss"));
                        Directory.Move(sourcedirectory, destinationdirectory);
                    }
                    else
                    {
                        Directory.Move(sourcedirectory, destinationdirectory);
                    }
                }
    
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }
    

提交回复
热议问题