RSS

Category Archives: System.IO

Get modified file/folders using C#.net

If there is a requirement for which you need to collect the files and folders which are modified in last 24 or 48 hours than the following two functions will give you the solution:

// Code starts

TimeSpan t = new TimeSpan(24, 0, 0); // you need to define the hour here
DateTime dtTargetDate = DateTime.Now.Subtract(t);

sourceDirectory: From which you want to collect latest modified files and folders.

targetDirectory: Where you want latest file/folder to be pasted.

dtTargetDate : The function will return you files/folders which modified date is greater than dtTargetDate

public static void CopyLastetDirectory(string sourceDirectory, string targetDirectory, DateTime dtTargetDate)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
try
{
CopyAllLastestFiles(diSource, diTarget, dtTargetDate);
}
catch (Exception ex)
{
throw ex;
}
finally
{
diSource = null;
diTarget = null;
}
}

public static void CopyAllLastestFiles(DirectoryInfo source, DirectoryInfo target, DateTime dtTargetDate)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}

// Copy each file into it’s new directory.
foreach (FileInfo fi in source.GetFiles())
{
//Console.WriteLine(@”Copying {0}\{1}”, target.FullName, fi.Name);
if (fi.LastWriteTime.Date >= dtTargetDate.Date && !fi.Name.Contains(“Web.config”))
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}

// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
// Folder names that you want to omit
if (diSourceSubDir.Name.Contains(“.svn”) || diSourceSubDir.Name.Contains(“Vagaro.BackupService”))
continue;
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAllLastestFiles(diSourceSubDir, nextTargetSubDir, dtTargetDate);
nextTargetSubDir = null;
}
}

That is it.

Happy Programming ! 🙂

 
Leave a comment

Posted by on July 20, 2010 in System.IO

 

Tags: , , , ,