Easy routine to check/create directories

By | 2002-06-01

This very simple routine avoid checking if a correct path already
exist before using it and, if not, create it exactly as you want.
Imagine you wont to write a log file in a path defined as:
C:MyapplicServiceslogsLOG.TXT
you must check before if the directory Myapplic exist and
then check all other subdirectory (Service,logs) before opening the
file For Output. Probably you will use a lot of Error Resume Next, Mkdir(…),
Error GoTo 0, dir(….) and so.
Instead you can use this routine as described below:
Myfile=”C:MyapplicServiceslogsLOG.TXT”
Call CheckDir(Myfile)
nf=FreeFile()
Open Myfile For Output As #nf
.
.
.
Close #nf
and including the following .bas module:
Public Sub CheckDir(file)
Ix = 4 ‘Initial index
KSlash = InStr(1, file, “”, 1) ‘Search for first “”
For Cnt = 1 To Len(file) ‘Run until discover
‘other directories
KSlash = InStr((KSlash + 1), file, “”, 1)
If KSlash = 0 Then Exit For ‘Last slash
dir1 = Left(file, (KSlash – 1))
cdir1 = Mid(dir1, Ix)
Ix = Ix + Len(cdir1) + 1
hh = Dir(dir1, vbDirectory)
‘If Directory doesn’t exist, create it
If StrComp(hh, cdir1, 1) <> 0 Then
MkDir (dir1)
End If
Next Cnt
End Sub

Original Author: Italo ALFIERI

API Declarations

Code

Public Sub CheckDir(file)
Ix = 4 'Initial index
KSlash = InStr(1, file, "", 1) 'Search for first ""
   For Cnt = 1 To Len(file) 'Run until discover
               'other directories
     KSlash = InStr((KSlash + 1), file, "", 1)
     If KSlash = 0 Then Exit For 'Last slash
     dir1 = Left(file, (KSlash - 1))
     cdir1 = Mid(dir1, Ix)
     Ix = Ix + Len(cdir1) + 1
     hh = Dir(dir1, vbDirectory)
     'If Directory doesn't exist, create it
     If StrComp(hh, cdir1, 1) <> 0 Then
       MkDir (dir1)
     End If
   Next Cnt
End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.