我的源目录“D:\ Source”
目的地“D:\目的地”
源目录包含一些具有不同创建日期的文件和文件夹, 我想移动创建日期少于过去5天的所有文件和文件夹 例如今天 28/11/2015 ,我想在创建23/11/205之前从源移动所有文件和文件夹。
我正在寻找2天但没有成功。
这是我的尝试
var sourcePath = "D:\\Source";
var destinationPath = "D:\\Destination";
var dInfo = new DirectoryInfo(sourcePath)
var files = (from filew in dInfo.EnumerateFiles(sourcePath)
orderby filew.CreationTime.Date < DateTime.Now.Date.AddDays(-5) ascending
select filew.Name).Distinct();
var directories = (from filew in dInfo.EnumerateDirectories(sourcePath)
orderby filew.CreationTime.Date < DateTime.Now.Date.AddDays(-5) ascending
select filew.Name).Distinct();
foreach (var dir in directories)
{
var dest = Path.Combine(destinationPath, Path.GetFileName(dir));
Directory.Move(dir, dest);
}
foreach (var file in files)
{
var dest = Path.Combine(destinationPath, Path.GetFileName(file));
File.Move(file, dest);
}
错误:第二个路径片段不能是驱动器或UNC名称。
请帮帮我
答案 0 :(得分:1)
您必须在没有参数的情况下致电EnumerateFiles
和EnumerateDirectories
:
dInfo.EnumerateFiles()
dInfo.EnumerateDirectories()
有关sourcePath
的信息已在dInfo
对象中。该参数将用于应用过滤器。
更新:
EnumerateFiles()
函数只返回没有pathes的文件名。所以你应该使用类似的东西:
foreach (var file in files)
{
var src = Path.Combine(sourcePath, file);
var dest = Path.Combine(destinationPath, file);
File.Move(src, dest);
}
答案 1 :(得分:0)
您需要以递归方式执行此操作,因为目录中可能存在相同规则的子目录。请参阅下面的代码。
public static void MoveFilesAndFolders(string sourcePath, string destinationPath)
{
var directories = Directory.GetDirectories(sourcePath);
foreach (var directory in directories)
{
var subDirectory = new DirectoryInfo(directory);
//Create sub directory in the destination folder if the business rules is satisfied
if (DateTime.Today.Subtract(File.GetCreationTime(directory)).Days < 5)
{
var newDestinationDirectory = Directory.CreateDirectory(Path.Combine(destinationPath, subDirectory.Name));
MoveFilesAndFolders(subDirectory.FullName, newDestinationDirectory.FullName);
}
}
foreach (var file in Directory.GetFiles(sourcePath))
{
var fileName = Path.GetFileName(file);
//Copy the file to destination folder if the business rule is satisfied
if (!string.IsNullOrEmpty(fileName))
{
var newFilePath = Path.Combine(destinationPath, fileName);
if (!File.Exists(newFilePath) && (DateTime.Today.Subtract(File.GetCreationTime(file)).Days < 5)))
{
File.Move(file, newFilePath);
}
}
}
}