Create file with directory structure

asphughes

Member
Joined
Jan 10, 2007
Messages
17
Location
London
Programming Experience
3-5
My probelm seems simple but I've not been able to find anything that works how I want.

I want to be able to check if a file exists and if it does not create that file along with the directory structure.

If

C:\FolderA\FolderB\File.txt does not exist

Then create

FolderA
FolderB
File.Txt

I found some code that worked if the whole path didn't exist but failed if the FolderA did already exist but not FolderB.
 
Public Function CreateFolder(ByVal destDir As String) As Boolean

Dim i As Long
Dim prevDir As String

On Error Resume Next

For i = Len(destDir) To 1 Step -1
If Mid(destDir, i, 1) = "\" Then
prevDir = Microsoft.VisualBasic.Left(destDir, i - 1)
Exit For
End If
Next i

If prevDir = "" Then CreateFolder = False : Exit Function
If Not Len(Dir(prevDir & "\", vbDirectory)) > 0 Then
If Not CreateFolder(prevDir) Then CreateFolder = False : Exit Function
End If

On Error GoTo errDirMake
MkDir(destDir)
CreateFolder = True
Exit Function

errDirMake:
CreateFolder = False

End Function

This works though seems to always return false despite folders being created
 
why dont you pass the sub a string being the folder structure (folder path) and in that sub split the folder path into an array (splitting on the dir char) then loop through the array checking to see if that part of the path exists, if it doesnt, make it.

VB.NET:
Imports System.IO

    Private Function MakeDirTree(ByVal Path As String) As Boolean
        Try
            Dim PathPiece() As String = Path.Split(IO.Path.DirectorySeparatorChar)
            Dim CurrentPath As String = PathPiece(0)
            For Counter As Integer = 1 To PathPiece.GetUpperBound(0)
                CurrentPath &= IO.Path.DirectorySeparatorChar & PathPiece(Counter)
                If Directory.Exists(CurrentPath) = False Then Directory.CreateDirectory(CurrentPath)
            Next Counter
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
            Return False
        End Try
    End Function
 
IO.Directory.CreateDirectory method:
Creates all directories and subdirectories as specified by path.
VB.NET:
Dim f As New IO.FileInfo("C:\FolderA\FolderB\File.txt")
If Not f.Directory.Exists Then
    IO.Directory.CreateDirectory(f.Directory.FullName)
End If
As for creating the file, look into the methods of FileInfo available, there are some option depending on what you want to do with the file or type of file.
 
Back
Top