ali yami ali yami - 17 days ago 7
C# Question

Filter Directory structure by Created date and then Copy using c#

I want to Filter files in an entire directory structure by created date property and then copy preserving this new filtered directory structure to the destination using c#.

I Have found a solution, but it does not filter.

using System;
using System.IO;

class CopyDir
{
public static void Copy(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

CopyAll(diSource, diTarget);
}

public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);

// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}

// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}

public static void Main()
{
string sourceDirectory = @"c:\sourceDirectory";
string targetDirectory = @"c:\targetDirectory";

Copy(sourceDirectory, targetDirectory);
}

// Output will vary based on the contents of the source directory.


}

Answer

Well after you told us you want to "filter" by the creation date you could do something like:

//If date is newer than 1 week
if(fi.CreationTime >= DateTime.Now - TimeSpan.FromDays(7))
   fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);