Link to home
Start Free TrialLog in
Avatar of mallards
mallards

asked on

Detecting existence of a directory

I want to check a specified drive for the existence of a directory.
If the directory doesn't currently exist I will then create it. If it does exist I will not worry about creating it.

How do I go about checking for the presence of a directory?
Avatar of Brendt Hess
Brendt Hess
Flag of United States of America image

This code can be used.

Dim S$
S = Dir("C:\TEMP\.",vbDirectory) ' change to match your directory.  The period is important

If S = "." Then
   ' It's a directory, and it exists!
Else
   S=Dir("C:\TEMP")
   If S <> "" Then
      ' some file of that name exists!
   Else
      ' MkDir "C:\TEMP"
   End If
End If
ASKER CERTIFIED SOLUTION
Avatar of Erick37
Erick37
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jagertee
Jagertee

Function ExistPath(MyPath) As Boolean
  On Error Resume Next

  Dim x as String

  'save current directory
  x = CurDir

  'try to change to MyPath
  ChDir MyPath
  If Err=0 Then
    'yes, it's there!
    ExistPath = True
  End If

  'back to current directory
  ChDir x

  Err = 0
End Function
Avatar of mallards

ASKER

Quicker and more efficient way to do it. see Erick37
Great! What efficient code. Thanks alot!
Thanks. Glad it helped!
Just a small warning - if a file exists with the same name as your proposed directory, then the test will return 'Directory Exists' (as of VB5 - Is this fixed in VB6?)
I think it's an operating system issue.  In Win95, you cannot have a file with the same name of a directory in the same level.
I know that - what I was noting was that, even though you specify vbDirectory on the DIR call, it will still return any files AND directories that match your spec, as if vbDirectory had not been specified.  This is a bug.

So, if I wanted to find out if the directory C:\Autoexec.BAT existed, the call would happily return that there was a directory of that name.  Try to ChDir to there, and... Error!