Jul 04 2004

Ensure directory exists

Posted by admin under .NET

This code snippet lets you specify a path - and the function then ensure it exists - i.e creates all folders if necessery.



        public static void EnsureDirectory(System.IO.DirectoryInfo oDirInfo)
        {
            if (oDirInfo.Parent != null)
                EnsureDirectory(oDirInfo.Parent);
            if (!oDirInfo.Exists)
            {
                oDirInfo.Create();
            }
        }


As you can see it works by recursively checking if the folder exists - and you need to feed it a DirectoryInfo object. However that is easily created from a simple string :

Example of usage:



EnsureDirectory(new System.IO.DirectoryInfo("c:\\hello\\test\\whatever"));


 It starts off with c:\\hello\\test\\whatever. If that path has a parent ( and it does ) it calls the function recursively - now with c:\\hello\\test\ as the path. Recersively calling all the way down to root - and there we check if the path exist - otherwise create it - up one level, check/create again. This ensures that all directories are created in the correct order.