等效于VB6中的Directory.CreateDirectory()

时间:2008-11-12 19:48:57

标签: vb6

尝试一次创建几层文件夹C:\ pie \ apple pie \ recipes \ 没有使用几个不同的命令,有一种类似于Directory.Create Directory()

的简单方法

4 个答案:

答案 0 :(得分:8)

这是我在其中一个项目中使用的一些代码。它需要将引用添加到文件系统对象的项目中。

首先,点击Project - >参考,向下滚动到“Microsoft Scripting Runtime”并选择它。然后你可以使用这个功能:

Public Sub MakePath(ByVal Folder As String)

    Dim arTemp() As String
    Dim i As Long
    Dim FSO As Scripting.FileSystemObject
    Dim cFolder As String

    Set FSO = New Scripting.FileSystemObject

    arTemp = Split(Folder, "\")
    For i = LBound(arTemp) To UBound(arTemp)
        cFolder = cFolder & arTemp(i) & "\"
        If Not FSO.FolderExists(cFolder) Then
            Call FSO.CreateFolder(cFolder)
        End If
    Next

End Sub

答案 1 :(得分:2)

'无需引用FileSystemObject

Public Sub MkPath(ByVal sPath As String)
  Dim Splits() As String, CurFolder As String
  Dim i As Long
  Splits = Split(sPath, "\")
  For i = LBound(Splits) To UBound(Splits)
    CurFolder = CurFolder & Splits(i) & "\"
    If Dir(CurFolder, vbDirectory) = "" Then MkDir CurFolder
  Next i
End Sub

答案 2 :(得分:0)

作为替代方案,这里是我编写的一个函数,它包含一个完整的路径,包括驱动器号(如果需要的话)作为参数。然后它走过路径并捕获VB错误号76(找不到路径)。当错误处理程序捕获错误76时,它会创建导致错误的文件夹并继续沿路径行走。

    Public Function Check_Path(rsPath As String) As Boolean
        Dim dPath As String
        Dim i As Integer
        Dim sProductName As String

        On Error GoTo Check_Path_Error

        If Left$(UCase$(rsPath), 2)  Left$(UCase$(CurDir), 2) Then
            ChDrive Left$(rsPath, 2)
        End If

        i = 3
        Do While InStr(i + 1, rsPath, "\") > 0
            dPath = Left$(rsPath, InStr(i + 1, rsPath, "\") - 1)
            i = InStr(i + 1, rsPath, "\")
            ChDir dPath
        Loop
        dPath = rsPath
        ChDir dPath

        Check_Path = True

    Exit Function

    Check_Path_Error:
        If Err.Number = 76 Then     'path not found'
            MkDir dPath             'create the folder'
        Resume
    Else
        sProductName = IIf(Len(App.ProductName) = 0, App.EXEName, App.ProductName)
        MsgBox "There was an unexpected error while verifying/creating directories." _
              & vbCrLf & vbCrLf & "Error: " & CStr(Err.Number) & ", " & Err.Description &  ".", _
            vbOKOnly + vbCritical, sProductName & " - Error Creating File"
        Check_Path = False
    End If

    End Function

答案 3 :(得分:0)

然而,另一种简单的方法是:

Public Sub MakePath(ByVal Path As String)
    On Error Resume Next
    Shell "cmd /c mkdir """ & Path & """"
End Sub