Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

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

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" error. Below is my code.

could any one suggest on this?

        string sourcedirectory = @"F:source";
        string destinationdirectory = @"F:destination";

        try
        {
            if (Directory.Exists(sourcedirectory))
            {
                if (Directory.Exists(destinationdirectory))
                {
                  Directory.Move(sourcedirectory, destinationdirectory);
                }
                else
                {
                  Directory.CreateDirectory(destinationdirectory);
                  Directory.Move(sourcedirectory, destinationdirectory);
                }
            }

        }
        catch (Exception ex)
        {
            log(ex.message);
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...