January 27, 2012

Exist or be Created!

Just encountered a collegue having difficulties ensuring if a folder exists. And if a folder does not exists then it has to be created in its full path, not only the lowest level folder. The code was bloated with if/then’s, instr(), instrrev() and left()/right() functions. Even the lowest level folder name was hardcoded.

To help him out, we could go for the fancy recursive solution to show off our 1337 programming skillz, but I decided to just do it with a simple loop. Enjoy.

Public Function EnsureFolder(fPath)
    dim fso, fols, fol, pathBuild
    set fso=CreateObject("Scripting.FileSystemObject")

    fols = split(fpath, "\")

    For each fol in fols
        If fol = "" Then exit for
        pathBuild = pathBuild & fol & "\"
        If Not fso.FolderExists(pathBuild) Then
            Call fso.CreateFolder(pathBuild)
        End If
    Next

    EnsureFolder = pathBuild
End Function

1 comment:

traininginstitute said...

I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at this place
full stack web development course