CodeItBetter Programming Another VB Programming Blog

Create Nested Directories (in two ways)

Posted on June 23, 2011
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'File/Folders Handling - Create Nested Directories (in two ways)
'Using API:

Option Explicit
 
Private Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" _
    (ByVal lpPath As String) As Long
 
Sub CreateDirectories()
    'This will create the directory "c:\this\is\a\test\directory\", if it doesn't exist already
    MakeSureDirectoryPathExists "c:\this\is\a\test\directory\"
End Sub
 
'Without Using API:

Public Function fnCreateDirectories(strPath As String)
'This function is used to create recursive directories
'This function will check for folder exist if doesn't exist then it will create it.
'For example: if strFolderPath = "C:\Temp\Testing\Temp\Testing\Temp\Testing" then
'It will check existance of the folders: C:, C:\Temp, C:\Temp\Testing, etc.
'If folders doesn't exist then it will create those folders.
'You can call this function as:
'Call CreateDirectories ("C:\Temp\Testing\Temp\Testing\Temp\Testing")
'This will create all directories and its subdirectories.

    Dim arrPath() As String
    Dim strTemp As String
    Dim i As Integer
    'strPath = "C:\Temp\Testing\Testing"

    On Error GoTo fnCreateDirectories_Error
 
    arrPath = Split(strPath, "\")
    For i = 0 To UBound(arrPath)
        'create folder paths
        If strTemp <> "" Then
            strTemp = strTemp & "\" & arrPath(i)
        Else
            strTemp = arrPath(i)
        End If
        'if folder doesn't exists then create it
        If Not fnFolderExists(strTemp) Then
            On Error Resume Next
            MkDir strTemp
        End If
    Next i
 
    On Error GoTo 0
    Exit Function
 
fnCreateDirectories_Error:
    Call MsgBox(Err.Number & " " & Err.Description, vbExclamation, App.Title)
End Function
 
Public Function fnFolderExists(strFolder As String) As Boolean
'Check if folder exists
    fnFolderExists = (Dir$(strFolder, vbDirectory) <> vbNullString)
End Function
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.