Easy .NET directory helper

Add this class to your C# project:

public class Directory
{
    private string _path;

    private Directory(string path)
    {
        _path = path;
    }

    public static Directory ApplicationData
    {
        get
        {
            return new Directory(Environment.GetFolderPath(
                Environment.SpecialFolder.ApplicationData));
        }
    }

    public static Directory CommonApplicationData
    {
        get
        {
            return new Directory(Environment.GetFolderPath(
                Environment.SpecialFolder.CommonApplicationData));
        }
    }

    public static Directory operator /(Directory root, string folder)
    {
        return new Directory(Path.Combine(root._path, folder));
    }

    public static implicit operator string(Directory directory)
    {
        return directory._path;
    }
}

Now you can express directories naturally:

string databaseFileName = Directory.ApplicationData / "MichaelLPerry" / "CorrespondenceIM" / "Correspondence.sdf";

I don’t have a good place for code like this to live. What do you do with these kinds of utilities?

Leave a Reply

You must be logged in to post a comment.