Copying a specific subfolder of a parent folder

by Mikael Henriksson 14. February 2010 01:23

I have a service that sends our application to customers based on various criteria's. I want to verify the most important parameters and to do that I of course need to copy the whole darn folder structure to the directory the tests are run from to simulate the web client.

To please both Team City and the R# test runner I had to create something of my own and I’d rather not lock that down to visual studio nor NAnt. I found this great class on MSDN that seems to do the trick.

 

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

		CopyAll(diSource, diTarget);
	}

	public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
	{
		if (source.Name.Contains(".svn"))
			return;
	   
		// 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);
			fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
		}

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

All I did was add a filter for “.svn” folders that I really don’t want to keep. I do want to delete the whole thing after the tests are run. I also added a method for recursively navigating the parents to find the desired folder.

public DirectoryInfo RecursivelySearchParents(DirectoryInfo startDir, string folder)
{
	var resultDir = startDir.GetDirectories().FirstOrDefault(x => x.Name == "sw");
	if (resultDir != null)
		if (resultDir.Exists)
			return resultDir;
			
	return RecursivelySearchParents(startDir.Parent, folder);
}

And then the SetUpFixture with it’s SetUp and TearDown attributes.

[SetUpFixture]
public class TestSetUp
{
	public static string BinaryTargetDir = 
		string.Intern(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sw"));
	public static string SourceDirectory;

	[SetUp]
	public void Setup()
	{
		var dir = new DirectoryInfo(Directory.GetCurrentDirectory())
		SourceDirectory = CopyDir.RecursivelySearchParents(dir, "sw").FullName;
		CopyDir.Copy(SourceDirectory, BinaryTargetDir);
	}
	
	[TearDown]
	public void TearDown()
	{
		var dir = new DirectoryInfo(BinaryTargetDir);
		dir.Delete(true);
	}
}

Tags:

C#

blog comments powered by Disqus