MakeDir recursive directory creation

	Function MakeDir
	Description: Create a directory with the specified path. Parent directories are also created, if
		they don't exist.
Sub MakeDir(ByVal strDir$)
	Dim stack$ ' the list of directories we need to create
	Dim parts, i%, ptr%

	strDir = Replace(strDir, "\", "/") ' / works on all OS and simplifies our code.
	strDir = Replace(strDir, "//", "/")
	If Right$(strDir, 1) = "/" Then strDir = StrLeftBack(strDir, "/")
	On Error 76 GoTo parentDoesNotExist
	MkDir strDir
	' if we got here, it worked.
	Exit Sub

parentDoesNotExist: ' failed because parent directory doesn't exist. Build an array of directories to attempt.
	Resume theLoop
	parts = Split(strDir, "/")
	For i = 1 To UBound(parts)
		parts(i) = parts(i-1) & "/" & parts(i)
	ptr = UBound(parts) - 1 ' ptr is index of directory to try to create.
	On Error 76 GoTo backup
	MkDir parts(ptr)
	' if we get here the create succeeded, and we only have to go forward in the list.
	On Error GoTo 0
	For i = ptr+1 To UBound(parts)
		MkDir parts(i)
	Exit Sub
	ptr = ptr - 1
	If ptr >= 0 Then
		If parts(ptr) = "" Then GoTo backup
		Resume tryAnother
	End If
	Error Err, Error ' ran out of higher level directories to try.
End Sub
All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.
1 comment(s)Login first to comment...
(at 07:48 on 19.12.2015)
This subroutine will, if necessary, create the entire path.