Mole is a simple solution that demonstrates how to off-load the collecting of file system information, such as the lengths and attributes of files, by using a separate process.

The solution, therefore, consists of the following two projects:

  • MOLE: mole is a console application, written in C++, that takes a directory path as a single parameter, and lists the contents (all files and sub-directories) of that directory.
  • MOLEDRIVER: MoleDriver is a C# console application that demonstrates how to execute mole out-of-process.
namespace MoleDriver
{
    using System;
    using System.Diagnostics;
    using System.Text;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var psi = new ProcessStartInfo("mole.exe", @"C:\Windows")
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                StandardOutputEncoding = Encoding.Unicode,
            };
            var p = Process.Start(psi);

            var so = p.StandardOutput;
            var c = 0;
            while (!so.EndOfStream)
            {
                var line = so.ReadLine();
                var tokens = line.Split(new[] { ',' }, 6);

                var creation = DateTime.Parse(tokens[0]);
                var lastAccess = DateTime.Parse(tokens[1]);
                var lastWrite = DateTime.Parse(tokens[2]);
                var length = long.Parse(tokens[3]);
                var attributes = long.Parse(tokens[4]);
                var path = tokens[5];
                c++;
            }
            Debug.WriteLine(c);

            p.WaitForExit();
        }
    }
}

“Now,” you might ask, “Why would I want to do any of this?” Good question.

If you’ve ever tried the EnumerateFiles or EnumerateDirectories calls of the .NET framework to get a complete list of all the files and directories on your C: drive, you must have noticed that you will invariably get a security exception. As far as I am concerned, that makes these call pretty much useless. The mole will not throw any exceptions. It will list everything it can access. If you don’t see it, it’s because you don’t have permission to see it.

The question, remains, though, why run the mole out of process? After all, we could achieve pretty much the same results by accessing the Win32 functions through Interop. That’s a valid point! Actually, I’ve also written a class library that does everything you see here with Interop calls - I’ll publish it later on. But Interop is not always a good idea, and it’s definitely not for everyone.

So, if you were looking for a fast way to list everything on a drive, here you are: