将文件夹(目录)从一个位置移动到另一个位置 - 不当行为

Sha*_*har 3 c# directory move

我想使用C#.NET将目录从一个位置移动到另一个位置.我使用Directory.Move甚至DirectoryInfo(使用MoveTo)这个简单的方法:

// source is: "C:\Songs\Elvis my Man"
// newLocation is: "C:\Songs\Elvis"

try
{
    // Previous command was: Directory.Move(source, newLocation);
    DirectoryInfo dir = new DirectoryInfo(source);
    dir.MoveTo(newLocation);
}
catch (Exception e)
{
    Console.WriteLine("Error: "+ e.Message);
}
Run Code Online (Sandbox Code Playgroud)

但是正在进行的操作(对于这两种情况)都是将文件夹名称从"source"重命名为"newLocation"

我的期望是什么?那个文件夹"Elvis my man"现在将出现在"Elvis"文件夹中.

发生了什么事?"我的男人猫王"改为"猫王"(改名).如果目录"Elvis"已经存在,则无法将其更改为"Elvis"(因为他不能创建重复的名称),因此我得到一个例外.

我究竟做错了什么??

非常感谢!!!

Tea*_*ild 6

我建议围绕Move命令进行验证,以确保源位置确实存在且目标位置不存在.

我总是发现避免异常比处理它们更容易.

您可能也希望包含异常处理,以防访问权限出现问题或文件已打开且无法移动...

以下是一些示例代码:

            string sourceDir = @"c:\test";
        string destinationDir = @"c:\test1";

        try
        {
            // Ensure the source directory exists
            if (Directory.Exists(sourceDir) == true )
            {
                // Ensure the destination directory doesn't already exist
                if (Directory.Exists(destinationDir) == false)
                {
                    // Perform the move
                    Directory.Move(sourceDir, destinationDir);
                }
                else
                {
                    // Could provide the user the option to delete the existing directory
                    // before moving the source directory
                }
            }
            else
            {
                // Do something about the source directory not existing
            }
        }
        catch (Exception)
        {
            // TODO: Handle the exception that has been thrown
        }
Run Code Online (Sandbox Code Playgroud)


Sam*_*Sam 5

尽管这在命令行中可以移动文件,但在编程时您需要提供完整的新名称。

因此,您需要将 newLocation 更改为“C:\Songs\Elvis\Elvis my Man”才能完成这项工作。