将文件夹(目录)从一个位置移动到另一个位置-错误行为
本文关键字:位置 另一个 移动 错误 一个 目录 文件夹 | 更新日期: 2023-09-27 18:08:00
我想使用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);
}
但是正在执行的操作(对于这两种情况)是将文件夹名称从'source'重命名为'newLocation'
我期望什么?文件夹"Elvis my man"现在将在"Elvis"文件夹中。
发生了什么事? "Elvis my man"改为"Elvis"(已改名)。如果目录"Elvis"已经存在,它不能将其更改为"Elvis"(因为它不能创建重复的名称),因此我得到一个异常说:
我做错了什么?
多谢! !
我建议在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
}
尽管这可以在命令行中移动文件,但在编程时需要提供完整的新名称。
因此,您需要将newLocation更改为"C:'Songs'Elvis'Elvis my Man"以使此工作
From MSDN,
此方法抛出IOException,例如,如果您试图将c:'mydir移动到c:'public,而c:'public已经存在。必须指定"c:'public'mydir"作为destDirName参数,或者指定一个新的目录名,如"c:'newdir"。
看起来你需要将newLocation
设置为C:'Songs'Elvis'Elvis my man
private void moveDirectory(string fuente,string destino)
{
if (!System.IO.Directory.Exists(destino))
{
System.IO.Directory.CreateDirectory(destino);
}
String[] files = Directory.GetFiles(fuente);
String[] directories = Directory.GetDirectories(fuente);
foreach (string s in files)
{
System.IO.File.Copy(s, Path.Combine(destino,Path.GetFileName(s)), true);
}
foreach(string d in directories)
{
moveDirectory(Path.Combine(fuente, Path.GetFileName(d)), Path.Combine(destino, Path.GetFileName(d)));
}
}