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

标签 c# directory move

我想使用 C# .NET 将目录从一个位置 move 到另一个位置。我以这种简单的方式使用了 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);
}

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

我期望什么?文件夹“Elvis my man”现在将位于“Elvis”文件夹中。

发生了什么事?“Elvis my man”已更改为“Elvis”(已更名)。如果目录“Elvis”已经存在,则无法将其更改为“Elvis”(因为他不能重名),因此我得到一个异常(exception)。

我做错了什么??

非常感谢!!!

最佳答案

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

我一直发现避免异常比在它们确实发生时处理它们更容易。

您可能还希望包括异常处理,以防访问权限出现问题或文件已打开且无法 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
        }

关于c# - 将文件夹(目录)从一个位置 move 到另一个位置 - 不当行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7361788/

相关文章:

c - 我的 move 算法无法正常工作

c++ - 使用 ncurses c++ (Linux) 将光标 move 到屏幕上的特定点

c# - 获取 OAuth2 刷新 token

c# - 部署我的应用程序后,我的用户如何添加 sprite 和图像资源?

azure - 如何将包含 terraform 文件的文件夹放入 docker 容器中并进一步将其部署到 azure

android - 如何使用 android 的可扩展 ListView 显示文件夹和文件列表?

javafx - 从 GridPane 中删除一行

c# - 为什么 `dotnet msbuild` 会在第一次运行时失败并显示警告,然后第二次运行成功?

c# - 如何上传/转换 *.docx 到谷歌文档?谷歌云端硬盘 API v3

Python pandas 从兄弟目录读取 CSV