Working With Directories in C#

I need to do a directory walk and decided to try coding it in C#.

You can use System.IO.DriveInfo to retrieve information on a given drive.

This is some dummy code on how to create a System.IO.DriveInfo object.

System.IO.DriveInfodrive drive = new System.IO.DriveInfo(@"C:\"); // Makes C Drive object
Console.WriteLine(drive.Name); // Output: "C:\"

You can also make an object of for the root directory from the drive object. Again here is some more dumb code.

System.IO.DirectoryInfo root = new drive.RootDirectory;

With DirectoryInfo objects you can retrieve both the files and sub-directories contained within that object. You can also target what kind of file or directories you what to collect. In this case I want to see everything and used a wild card character.  If you want to only see text files, you can use something like this “*.txt”.

System.IO.FileInfo[] files = root.GetFiles("*.*");
System.IO.DirectoryInfo[] subDirs = root.GetDirectories("*.*");

That’s where I’m going to leave off. Read the MSDN guide mentioned at the end of this post on how to do a recursive directory walk.

I also included a striped down version of two wrapper classes I made for myself.  This wrapper class is for the DriveInfo.

class Drive{
        private System.IO.DriveInfo info;

        // - Constructor
        public Drive(String path) {
            info = new System.IO.DriveInfo(path);
        }

        // - Getters
        public System.IO.DriveInfo     get()                   { return this.info; }
        public long                    getAvailableFreeSpace() { return this.info.AvailableFreeSpace; }
        public string                  getDriveFormat()        { return this.info.DriveFormat; }
        public bool                    getIsReady()            { return this.info.IsReady; }
        public string                  getName()               { return this.info.Name; }
        public System.IO.DirectoryInfo getRootDirectory()      { return this.info.RootDirectory; }
        public long                    getTotalFreeSpace()     { return this.info.TotalFreeSpace; }
        public long                    getTotalSize()          { return this.info.TotalSize; }
        public string                  getTotalVolumeLabel()   {
            if (this.info.VolumeLabel != "")
                return this.info.VolumeLabel;
            else
                return "None";
        }
    }

If you read the MSDN article, this little code snippet might come in handy for you to write your own drives wrapper class. In my case, I just created a list to hold each drive.

string[] drives = System.Environment.GetLogicalDrives();
foreach (string dr in drives)
{
            System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
. . .

I also made this directory object to mainly because I wanted to yield each file and sub-directory.

    class Directory {
        private System.IO.FileInfo[]      files;
        private System.IO.DirectoryInfo[] subDirs;
        public Directory(DirectoryInfo dir) {
            this.files = dir.GetFiles("*.*");
            this.subDirs = dir.GetDirectories("*.*");
        }
        // Getters
        public System.IO.FileInfo[]      getFiles()          { return this.files; }
        public System.IO.DirectoryInfo[] getSubDirectories() { return this.subDirs; }

        // Iterables
        public System.Collections.IEnumerable yieldFiles() {
            foreach (var file in this.files)
                yield return file;
        }
        public System.Collections.IEnumerable yieldSubDirectories() {
            foreach (var dir in this.subDirs)
                yield return dir;
        }
    }

Here is the my test, I won’t show you my output but this is how the wrapper objects work.

class Program {
        static void Main(string[] args) {
            Drive drive = new Drive(@"C:\");
            Console.WriteLine("Drive Class Test");
            Console.WriteLine("Available Free: " + drive.getAvailableFreeSpace() );
            Console.WriteLine("Format: " + drive.getDriveFormat() );
            Console.WriteLine("IsReady: "+ drive.getIsReady() );
            Console.WriteLine("Name: "+ drive.getName() );
            //There are few more things you can do with the root dir...
            Console.WriteLine("Root Dir Creation Time: "+ drive.getRootDirectory().CreationTime);
            Console.WriteLine("Total Free: "+ drive.getTotalFreeSpace() );
            Console.WriteLine("Total Size: " + drive.getTotalSize() );
            Console.WriteLine("Volume Lable: "+ drive.getTotalVolumeLabel() );

            Console.WriteLine();
            Console.WriteLine("Directory Class Test");

            Directory dir = new Directory(drive.getRootDirectory() );

            Console.WriteLine("Files in " + drive.getName());
            foreach( var file in dir.getFiles())
                Console.WriteLine(file);

            Console.WriteLine("Sub-Directories in " + drive.getName());
            foreach (var sub in dir.yieldSubDirectories())
                Console.WriteLine(sub);

            Console.ReadLine();
        }
    }

Additional Reading
How to: Iterate Through a Directory Tree (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/bb513869.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s