I wonder how I can see if an Directory exists with an "if" statment
Printable View
I wonder how I can see if an Directory exists with an "if" statment
VB Code:
If Len(Dir([i]"filename"[/i]) > 0 Then ' it exists Else ' it doesn't End If
Nobody better recommend that POS FileSystemObject.
Try this...
Hope this helps... Oh, and you might want to look into the FSO... :pCode:Private Function DirectoryExists(ByVal strDirectory As String) As Boolean
If (Right(strDirectory, 1) <> "\") Then
strDirectory = strDirectory & "\"
End If
If Dir(strDirectory, vbDirectory) <> "" Then
DirectoryExists = True
Else
DirectoryExists = False
End If
End Function
'Usage
Msgbox DirectoryExists("C:\Windows")
Laterz
wot, the FileSystemObject from the sccrun.DLL file scripting object ? Tht FileSystemObject?
Why not ?
:D
Indeed. Add the Microsoft Scripting Runtime to your References:
Before the FSO flame wars hit again, this is just an alternate method to file ops.Code:Dim FSO As New FileSystemObject
MsgBox FSO.FolderExists("C:\TestMe")
The Dir() Method works just as well.
Nobody better recommend that POS FileSystemObject.
You risk the wrath of Filburt1 ...
:eek:
Don't add unneeded references to a project. VB beginners 101. Simple logic. If the built in functions work, why import a more complex and larger beast?Quote:
Originally posted by Timwit
wot, the FileSystemObject from the sccrun.DLL file scripting object ? Tht FileSystemObject?
Why not ?
:D
*chuckle* As you can see, some people prefer it, others don't, much like cheese or spinach. If you want to keep your distribution size down, don't use the FSO even though it is a small 145k as opposed to some of the other controls which can hit a meg or more.
It boils down to personal preference :) If you want the functionality of the FSO but not the reference to your project, write your own class or module that encapsulates the intrinsic functions you need in methods.
Nicely said. :)
It does have some advantages, like a ton of built-in functions.
I would tend to agree with Filburt...theres no need for FSO unless your going to use a lot of its functions. BTW heres a more compact funciton that does that same thing as the code in the previous posts.
VB Code:
The code that was here was wrong!! look way down for the real code
This code does exactly the same thing as Digitral-X-Treme's code...only its 2 lines intead of 10;) .
hey
Can i have some cheese?
Do yourself a favor and test your code before posting it :)Quote:
Originally posted by nishantp
I would tend to agree with Filburt...theres no need for FSO unless your going to use a lot of its functions. BTW heres a more compact funciton that does that same thing as the code in the previous posts.
VB Code:
Function DirExist(Path As String) As Boolean If Right(Path, 1) <> "\" Then Path = Path & "\" DirExist = Dir(Path) <> "" End Function
This code does exactly the same thing as Digitral-X-Treme's code...only its 2 lines intead of 10;) .
First off, change it so Path is passed by value, since you're changing it within the function:
Function DirExist(ByVal Path As String) As Boolean
..but that's not why I'm posting this message. The reason why the other function takes up so many more lines is because it actually checks for the existence of a directory, not a file. All your function will look for is a file. Test it out, and it will insist that c:\msdos.sys exists (if you're running win9x), but c:\windows doesn't (whether or not it's your windows directory).
The fact that VB passes ByRef as default is a little cheesy in my book. But I'd have to agree, pass ByVal unless you want errors cropping up. I still like FSO, but that's because I use alot of it's functions :)
Dimension: Sure, do you want Cheddar, Swiss, Wesleydale (sp?), Bleu, or Fetta?
Sorry, sorry, I did test it...just not enough. The above code it wrong, it works but only on root directories...not sub dirs. This code does the trick (has been tested properly) :) :
Thanks for the pointers TygurVB Code:
The code that was here was wrong!! look down for the real code...
I'm guessing you didn't test its reaction to files :)Quote:
Originally posted by nishantp
Sorry, sorry, I did test it...just not enough. The above code it wrong, it works but only on root directories...not sub dirs. This code does the trick (has been tested properly) :) :
Thanks for the pointers TygurVB Code:
Function DirExist(ByVal Path As String) As Boolean If Right(Path, 1) <> "\" Then Path = Path & "\" DirExist = Dir(Path, vbDirectory) <> "" End Function
It will return true if you give it a file. Since it's supposed to check for the existence of a directory, not a file, it should return false.
EDIT: I just tested it myself, and I found that it gives an error if you give it a filename, instead of just returning true. The function posted by [Digital-X-Treme] does the same thing.
I agree...the default should be ByVal..i mean how many times do we use ByRef's capabilities compared with ByVal?
PS - you forgot to offer Motzerella Excalibur...
Yeah but im guessing the person knows whether there testing for the existance of a file or a directory. My code gives an error if a filename is provided. Lol and im 2 lazy to bother writing code to fix that...Quote:
Originally posted by Tygur
I'm guessing you didn't test its reaction to files :)
It will return true if you give it a file. Since it's supposed to check for the existence of a directory, not a file, it should return false.
Actually, the code to fix it is very simple. Just put this line as the first line of the function:Quote:
Originally posted by nishantp
Yeah but im guessing the person knows whether there testing for the existance of a file or a directory. My code gives an error if a filename is provided. Lol and im 2 lazy to bother writing code to fix that...
On Error Resume Next
Ya true. Thanks tygur.
VB Code:
Function DirExist(ByVal Path As String) As Boolean On Error Resume Next If Right(Path, 1) <> "\" Then Path = Path & "\" DirExist = Dir(Path, vbDirectory) <> "" End Function
THIS IS THE FINAL VERSION
Why do you need the error handling? The function i posted, works without error checking, as it checks the return from the dir function... Try it.
:):):)Code:Private Function DirectoryExists(ByVal strDirectory As String) As Boolean
If (Right(strDirectory, 1) <> "\") Then
strDirectory = strDirectory & "\"
End If
If Dir(strDirectory, vbDirectory) <> "" Then
DirectoryExists = True
Else
DirectoryExists = False
End If
End Function
MsgBox DirectoryExists("afendows") 'False
MsgBox DirectoryExists("C:\Windows\") 'True
MsgBox DirectoryExists("C:\Windows") 'True
MsgBox DirectoryExists("@") 'False
Laterz
Lol Tygur just pointed all that out Digital...try pointing your function to a file instead of a dir. It'll give an error.
Also...our functions are doing exactly the same thing. Your doing If dir(FilePath, vbDirectory) <>"" then ... so if dir(FilePath, vbDirectory) <>"" evaluates to true, then you hard coded it to give true. I just got rid of the if statement all together because your doing the same thing twice. The statement will either return true of false anyways. I know i could have explained it better...but thats the concept. :)
nishantp, the function i supplied DOES NOTreturn an error when checking for a file...
The function i supplied specifically uses the vbDirectory attribute to check if the target is 'directory related'. If it isn't, then it returns false! :rolleyes:
Laterz
Out of curiosity, did you test it at all to see what happens when you give it a file? I doubt it. I suggest you go ahead and test it before you make an even bigger fool of yourself :)Quote:
Originally posted by [Digital-X-Treme]
nishantp, the function i supplied DOES NOTreturn an error when checking for a file...
The function i supplied specifically uses the vbDirectory attribute to check if the target is 'directory related'. If it isn't, then it returns false! :rolleyes:
Laterz
*chuckle*
"Runtime Error 52: Bad Filename or Number"
Returns True because I'm looking for the parent folder name.Code:Dim fso As New FileSystemObject
MsgBox fso.FolderExists(fso.GetParentFolderName("C:\program files\desktop.ini"))
Returns False because I specified a file.Code:Dim fso As New FileSystemObject
MsgBox fso.FolderExists("C:\program files\desktop.ini")
No errors occured. FSO has some uses, and I say add it to your references for every project! MUAHAHAHAHAHA
nishantp's final copy of the DirExist function works just as well. It's just [Digital-X-Treme]'s function that returns the error now :)
FSO is not needed. Everyone, please ignore ExcalibursZone's post :D
*knocks out ExcalibursZone and starts kicking him* NO FSO! NO FSO! :DQuote:
Originally posted by ExcalibursZone
...FSO has some uses, and I say add it to your references for every project! MUAHAHAHAHAHA
hello? anybody home?Have you even bothered trying it out?? I gives an error for files!! I mean ok i didnt test mine properly at first. But after someone tells me it doesnt work i tested it and made the changes. And if you look at both our functions properly you will notice that they do exactly the same thing!!Quote:
Originally posted by [Digital-X-Treme]
nishantp, the function i supplied DOES NOTreturn an error when checking for a file...
The function i supplied specifically uses the vbDirectory attribute to check if the target is 'directory related'. If it isn't, then it returns false! :rolleyes:
Laterz
Hmmm.... :rolleyes:
Yes i did test it. I test all my code before posting, thoroughly. I have used this function in a number of my projects.Quote:
Originally posted by Tygur
Out of curiosity, did you test it at all to see what happens when you give it a file?
Why?! :rolleyes:Quote:
Originally posted by Tygur
I doubt it.
OK. Just to PROVE i have 'tested it' before i make an even 'bigger fool of myself' as you put it, here is some results.Quote:
Originally posted by Tygur
I suggest you go ahead and test it before you make an even bigger fool of yourself
The function works for me. You are obviously getting some sort of error. Please post the code you are using and the results you get from calling the function and the argument so i can see whats going on.Code:Private Sub Form_Load()
' 'C:\Command.com' - File
' Predicted return: False
MsgBox DirectoryExists("C:\Command.com")
' Return: False
' This is correct, as the file isn't a directory, it's a file...
' 'C:\Windows' - Directory
' Predicted return: True
MsgBox DirectoryExists("C:\Windows")
' Return: True
' This is correct, as the directory is a directory, and NOT a file.
End Sub
Private Function DirectoryExists(ByVal strDirectory As String) As Boolean
If (Right(strDirectory, 1) <> "\") Then
strDirectory = strDirectory & "\"
End If
If Dir(strDirectory, vbDirectory) <> "" Then
DirectoryExists = True
Else
DirectoryExists = False
End If
End Function
Anyone else got any contributions on whether the function works?
Laterz
*ROFL* it does indeed work well ;) Kudos to nishantp (kudos ... mmm reminds me of mail order monsters ...)
I like FSO :P but to each his own :D
Nooooooooo!! See what we've done!! Were arguing over stupid stuff like this and Excalibur is laughing his head off with his FSO...Listen people FSO is a cult. Dont let yourself be sucked in...:DQuote:
Originally posted by ExcalibursZone
*chuckle*
"Runtime Error 52: Bad Filename or Number"
Returns True because I'm looking for the parent folder name.Code:Dim fso As New FileSystemObject
MsgBox fso.FolderExists(fso.GetParentFolderName("C:\program files\desktop.ini"))
Returns False because I specified a file.Code:Dim fso As New FileSystemObject
MsgBox fso.FolderExists("C:\program files\desktop.ini")
No errors occured. FSO has some uses, and I say add it to your references for every project! MUAHAHAHAHAHA
Well, my avatar should tell you all about my mental state :D
Damn straight! Don't let the bytes get you! Look what they did to me! I mutated into a turtle! :)Quote:
Originally posted by nishantp
FSO is a cult. Dont let yourself be sucked in...:D
Does c:\command.com really exist? If you have win9x/me, try it on c:\msdos.sys (you probably do, since you expect command.com to be in c:\). Basically make sure the file you're testing it with really exists.Quote:
Originally posted by [Digital-X-Treme]
The function works for me. You are obviously getting some sort of error. Please post the code you are using and the results you get from calling the function and the argument so i can see whats going on.
Anyone else got any contributions on whether the function works?
Laterz
I'm getting the error no matter what file I try it on.
Look man i copied and pasted your code (i doubt even my computer could screw that up). I used the function to point to "c:\winnt\win.ini" which exists. And it gave me error 52 "Bad Filename or Number". Your function adds the "\" to the end of "C:\winnt\win.ini" to make "C:\winnt\win.ini\" And it gives the error. You could hardcode a way out of that but instead Tygur told me the easier way: On Error Resume Next. Come on man my function is 3 lines long. it shouldnt be very hard to understand here...Quote:
Originally posted by [Digital-X-Treme]
Hmmm.... :rolleyes:
Yes i did test it. I test all my code before posting, thoroughly. I have used this function in a number of my projects.
Why?! :rolleyes:
OK. Just to PROVE i have 'tested it' before i make an even 'bigger fool of myself' as you put it, here is some results.
The function works for me. You are obviously getting some sort of error. Please post the code you are using and the results you get from calling the function and the argument so i can see whats going on.Code:Private Sub Form_Load()
' 'C:\Command.com' - File
' Predicted return: False
MsgBox DirectoryExists("C:\Command.com")
' Return: False
' This is correct, as the file isn't a directory, it's a file...
' 'C:\Windows' - Directory
' Predicted return: True
MsgBox DirectoryExists("C:\Windows")
' Return: True
' This is correct, as the directory is a directory, and NOT a file.
End Sub
Private Function DirectoryExists(ByVal strDirectory As String) As Boolean
If (Right(strDirectory, 1) <> "\") Then
strDirectory = strDirectory & "\"
End If
If Dir(strDirectory, vbDirectory) <> "" Then
DirectoryExists = True
Else
DirectoryExists = False
End If
End Function
Anyone else got any contributions on whether the function works?
Laterz
Yeah, *Cough, it aint that hard to understand...Quote:
I used the function to point to "c:\winnt\win.ini" which exists. And it gave me error 52 "Bad Filename or Number". Your function adds the "\" to the end of "C:\winnt\win.ini" to make "C:\winnt\win.ini\" And it gives the error. You could hardcode a way out of that but instead Tygur told me the easier way: On Error Resume Next. Come on man my function is 3 lines long. it shouldnt be very hard to understand here...
My function will check if a DIRECTORY, named "C:\winnt\win.ini\" exists. On your system, this directory doesn't exist, so the function should return false, with no errors.Quote:
Your function adds the "\" to the end of "C:\winnt\win.ini" to make "C:\winnt\win.ini\" And it gives the error...
Look, this is getting stupid. Fact is, it works for me (using Win 98 SE, VB6 Pro, SP4), and i dont give a **** if it doesn't work for you. Patronise me all you like, but i know i am correct :rolleyes:
I noted you are using NT... Could be your problem...
Laterz
Im not exactly the only one. Tygur and Excalibur also tried your code and got the same results (Runtime error 52). But of course...you still know your right...(just i little ignorant there pal)...
I DID!!!!!!!!!!!!!!!!!!!!!
VB Code:
Function DirExist(ByVal Path As String) As Boolean On Error Resume Next If Right(Path, 1) <> "\" Then Path = Path & "\" DirExist = Dir(Path, vbDirectory) <> "" End Function
Come on filburt dont flip over to the dark side (FSO)...
Actually, you probably should care about whether or not it works on other people's computers. You should try your best to make sure your programs work on as many computers as possible.Quote:
Originally posted by [Digital-X-Treme]
Look, this is getting stupid. Fact is, it works for me (using Win 98 SE, VB6 Pro, SP4), and i dont give a **** if it doesn't work for you. Patronise me all you like, but i know i am correct :rolleyes:
I noted you are using NT... Could be your problem...
Laterz
I tested it out in Win98 and it does return false, so this does look like a WinNT/2000 (and very likely XP) issue. But I think you should care that it doesn't work right on non-Win9X/ME computers.
Look, nishantp dude... After reading another post on directory attributes (http://www.vbforums.com/showthread.p...threadid=93125), it's obvious that this is a platform specific problem. NT/Win2000 seems to have problems with directory and file attributes in VB, but Win 98 and 95 doesn't. Basically, the function will work for me, but not for you guys, because...
ExcalibursZone - Running Win2k.
nishantp - Running NT
Tygur - Running Win 2K
nishantp, i wasn't being ignorant, i am just trying to get my point across to people who have been patronising me throughout this post, trying to get their points over...
Laterz
[Digital-X-Treme],
Both our posts came at about the same time, and I just want to make sure you saw my post. Did you see it?
And of course, there is always the API, which I think (though I'm not on my Win2K machine to make sure) can do the search without error. Unfortunately, it false behind nishantp's example in terms of simplity.
VB Code:
'=============== 'In a Module '=============== Private Const FILE_ATTRIBUTE_ARCHIVE = &H20 Private Const FILE_ATTRIBUTE_COMPRESSED = &H800 Private Const FILE_ATTRIBUTE_DIRECTORY = &H10 Private Const FILE_ATTRIBUTE_HIDDEN = &H2 Private Const FILE_ATTRIBUTE_NORMAL = &H80 Private Const FILE_ATTRIBUTE_READONLY = &H1 Private Const FILE_ATTRIBUTE_SYSTEM = &H4 Private Type FILETIME dwLowDateTime As Long dwHighDateTime As Long End Type Private Type WIN32_FIND_DATA dwFileAttributes As Long ftCreationTime As FILETIME ftLastAccessTime As FILETIME ftLastWriteTime As FILETIME nFileSizeHigh As Long nFileSizeLow As Long dwReserved0 As Long dwReserved1 As Long cFileName As String * 260 cAlternate As String * 14 End Type Private Declare Function FindFirstFile Lib "kernel32.dll" _ Alias "FindFirstFileA" (ByVal lpFileName As String, _ lpFindFileData As WIN32_FIND_DATA) As Long Private Declare Function FindClose Lib "kernel32.dll" _ (ByVal hFindFile As Long) As Long Public Function DirExists(ByVal str_Dir As String) As Boolean Dim lng_handle As Long Dim typ_fileinfo As WIN32_FIND_DATA '============================================ 'In Win95/98/ME, you cannot have an ending 'backslash on a directory, otherwise it 'returns false. I would image its the same 'on WinNT/Win2K '============================================ If Trim$(Right$(str_Dir, 1)) = "\" Then str_Dir = Left$(str_Dir, Len(str_Dir) - 1) End If lng_handle = FindFirstFile(str_Dir, typ_fileinfo) If lng_handle = -1 Then DirExists = False FindClose lng_handle Exit Function Else If typ_fileinfo.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY Then DirExists = True Else DirExists = False End If End If FindClose lng_handle End Function
Usage:
VB Code:
Private Sub Command1_Click() If DirExists("c:\windows") Then: MsgBox "Windows Directory Exists" If DirExists("c:\program files\marcedit\") Then: MsgBox "MarcEdit directory Exists" If DirExists("c:\windows\desktop\count.vbs") = False Then: MsgBox "This is a file, not a directory" End Sub
With nishantp's code, you only add two lines of code (Not including the Function and End Function lines) and you remove the extra dependancy that the FSO brings on. Works for me!Quote:
Originally posted by ExcalibursZone
I believe nishantp has done it well. It works. It's small, and it uses intrinsic methods in VB. Mine was only 1 line long, though if you count the Dim of the FSO it's 2. Though nobody seems to like the simplicity of it :rolleyes: Oh, well :D I say Kudos to nishantp (rehash, yes, but a double kudo thread weeheehee)
Wow. It falls way behind.. I tested it out on my computer (Win2K) and it works flawlessly. This is good for when you want to find out if a directory exists while you're in a loop using the Dir() function to get all the files (or subdirectories, or both) in a directory. Anyone who's ever tried it knows exactly what I'm talking about :)Quote:
Originally posted by reeset
And of course, there is always the API, which I think (though I'm not on my Win2K machine to make sure) can do the search without error. Unfortunately, it false behind nishantp's example in terms of simplity.