我想使用 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/