Created
Directory Traversal in C#
I am reading through a chapter on binary trees. The first simple example they give is traversing through directory structures. As the book is for java the attached file is the example translated to c#.
Once I have finished the chapter I will upload the binary tree example translated to c#.
Here is an example postorder recursion through a directory tree (attachment main.cs). See attachment Main.cs for a different example.
using System.IO;
class RecurseDirectory
{
public static void Main(string[] args)
{
RecurseDirectory r = new RecurseDirectory();
RecurseDirectory.PrintDirsRecursively(new System.IO.DirectoryInfo(@"\\Directory\Location"), 0);
Console.Read();
}
public static void PrintDirsRecursively(System.IO.DirectoryInfo source, int depth)
{
foreach (System.IO.DirectoryInfo dir in source.GetDirectories())
{
PrintTabs(depth);
System.Console.WriteLine(source.FullName);
PrintDirsRecursively(dir, depth+1);
}
foreach (System.IO.FileInfo file in source.GetFiles())
{
PrintTabs(depth);
System.Console.WriteLine(file.FullName);
}
}
private static void PrintTabs(int depth)
{
for (int j=0; j < depth; j++)
{
System.Console.Write("\t");
}
}
}
Here is a simple recursive directory/file copy function.
using System.IO;
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
foreach (DirectoryInfo dir in source.GetDirectories())
{
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
}
foreach (FileInfo file in source.GetFiles())
{
file.CopyTo(Path.Combine(target.FullName, file.Name), true); //overwrite
}
}