使用Directory.Move时,如果该文件已存在,则无法创建文件 [英] Cannot create a file when that file already exists when using Directory.Move

查看:77
本文介绍了使用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.

有人可以建议吗?

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

推荐答案

前面的两个答案都指出,目标目录不存在.在您的代码中,如果目录不存在,则在创建该目录,然后尝试移动目录,Move方法将为您创建目录.如果目录已经存在,则需要将其删除或移动.

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.

类似这样的东西:

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

这篇关于使用Directory.Move时,如果该文件已存在,则无法创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆