Friday, August 13, 2010

System.IO.DirectoryInfo extension method: Recursively print directory structure

Yeah, lots of extension method posts today. I'm just going through my projects and posting the good ones.

Actually, this is one I did when I was looking at editing a .xlsx doc without Excel installed. It turns out that .xlsx docs are actually zip files. When decompressed, it's got several levels of directories. I wanted to show someone the directory structure on a forum, but I didn't feel like typing it all out, so I typed (more) code to do it for me. Amazing how we'll waste effort writing a program for something that was probably faster to do without it.

I also used it as an excuse to learn about default parameters. C# now supports them. You could call this method by providing just one parameter, because all the others are provided automatically. Also note that you can use any TextWriter, not just Console.Out. You could make a StreamWriter and output it to text.

Anyway, that was off topic. Here's the code.

using System.IO;

namespace DirectoryExtensions
    public static class DirectoryExtensions
        public static void PrintDirectoryStructure(this DirectoryInfo directory, TextWriter writer, string prefix = ">", string spacer = "--")
            writer.WriteLine(string.Format("{0}{1} (dir)", prefix, directory.Name));
            prefix = spacer + prefix;
            foreach (FileInfo file in directory.GetFiles())
                writer.WriteLine(string.Format("{0}{1} (file)", prefix, file.Name));
            DirectoryInfo[] subDirectories = directory.GetDirectories("*", SearchOption.TopDirectoryOnly);
            if (subDirectories.Length > 0)
                foreach (DirectoryInfo subDirectory in subDirectories)
                    PrintDirectoryStructure(subDirectory, writer, prefix, spacer);

Here's a use case:
DirectoryInfo directory = new DirectoryInfo(@"c:\dev\test");

Expected output:
>test (dir)
-->subdir1 (dir)
---->textfile.txt (file)
---->subdirA (dir)
---->subdirB (dir)
------>asdf.txt (file)
------>some text file.txt (file)
-->subdir2 (dir)
---->some text file.txt (file)
-->subdir3 (dir)

No comments:

Post a Comment

Speak your mind.