What would be the best way to figure out if a certain file exists? I was thinking about using the File System Objects. Does anybody know how to do this?
Printable View
What would be the best way to figure out if a certain file exists? I was thinking about using the File System Objects. Does anybody know how to do this?
It's a little easier than that:Quote:
Originally posted by bezaman
What would be the best way to figure out if a certain file exists? I was thinking about using the File System Objects. Does anybody know how to do this?
eg:
this will show a message if the file Test.Txt exists in the folder C:\Temp
If Dir("c:\temp\test.txt") <> "" Then Msgbox "File Exists!"
Here are some functions to check if a file or folder exist.
VB Code:
'******************************************************************************* '** Function: FileExists '** Parameters: '** FilePath (String) - the full path of a file '** Returns: True if the file exists, false otherwise '******************************************************************************* Public Function FileExists(FilePath As String) As Boolean If Len(FilePath) = 0 Then FileExists = False Else If Len(Dir$(FilePath)) > 0 Then FileExists = True Else FileExists = False End If End If End Function '******************************************************************************* '** Function: DirectoryExists '** Parameters: '** DirectoryPath (String) - the full path of a directory '** Returns: True if the directory exists, false otherwise '******************************************************************************* Public Function DirectoryExists(DirectoryPath As String) As Boolean If Len(DirectoryPath) = 0 Then DirectoryExists = False Else If Len(Dir$(DirectoryPath, vbDirectory)) > 0 Then DirectoryExists = True Else DirectoryExists = False End If End If End Function
Ive had mixed results using Dir for detecting presence of files (I have seen it "lie"). Anyway I came across this on the forums and it hasnt let me down yet:
VB Code:
Public Declare Function PathFileExists Lib "shlwapi.dll" _ Alias "PathFileExistsA" (ByVal pszPath As String) As Long Public Function FileExists(strpath As String) As Boolean If PathFileExists(strpath) = 1 Then FileExists = True Else FileExists = False End If End Function
Caveat is that shlwapi.dll will show up as a dependency and will be added to your install. When you try to install your app, Windows will complain about shlwapi.dll (in use I think). Anyway, just delete this dll from your install and youll be fine.
I personally use this function (since as Muddy mentions, DIR will lie if you pass it a valid directory instead of a file without checking the attributes)
VB Code:
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 FindFile(ByVal sSource As String) As Boolean Dim hsearch As Long Dim findinfo As WIN32_FIND_DATA Dim success As Long Dim Buffer As Long Dim retval As Long ' Begin a file search: hsearch = FindFirstFile(sSource, findinfo) If hsearch = -1 Then ' no files match the search string FindFile = False Else FindFile = True End If ' Close the file search handle retval = FindClose(hsearch) End Function
Or if you are still interested in the FSO way :
VB Code:
CHECKS FOR THE EXISTANCE OF A FILE Function FILEEXISTS(ByVal lsFilename As String) As Boolean On Error Resume Next Dim FSO As New Scripting.FileSystemObject FILEEXISTS = FSO.FILEEXISTS(lsFilename) Set FSO = Nothing End Function ' CHECKS FOR THE EXISTANCE OF A FOLDER Function FOLDEREXISTS(ByVal lsFilename As String) As Boolean On Error Resume Next Dim FSO As New Scripting.FileSystemObject FOLDEREXISTS = FSO.FOLDEREXISTS(lsFilename) Set FSO = Nothing End Function
I fixed the functions I posted before to behave correctly when checking directories....can anyone find anything wrong with them now?
VB Code:
'**************************************************** '** Function: FileExists '** Parameters: '** FilePath (String) - the full path of a file '** Returns: True if the file exists, false otherwise '**************************************************** Public Function FileExists(FilePath As String) As Boolean If Len(FilePath) = 0 Then FileExists = False Else If Len(Dir$(FilePath)) > 0 Then 'Make sure it's not a directory If (GetAttr(FilePath) And vbDirectory) <> vbDirectory Then FileExists = True Else FileExists = False End If Else FileExists = False End If End If End Function '**************************************************** '** Function: DirectoryExists '** Parameters: '** DirectoryPath (String) - the full path of a directory '** Returns: True if the directory exists, false otherwise '**************************************************** Public Function DirectoryExists(DirectoryPath As String) As Boolean If Len(DirectoryPath) = 0 Then DirectoryExists = False Else If Len(Dir$(DirectoryPath, vbDirectory)) > 0 Then If (GetAttr(DirectoryPath) And vbDirectory) = vbDirectory Then DirectoryExists = True Else DirectoryExists = False End If Else DirectoryExists = False End If End If End Function
Hi guys,
i have some slightly complicated issue with file exists.
i need to check the file in multiple level directory structure.
for eg :
i have Directory MAIN
also i have subfolders SUB1, SUB2 inside MAIN
i would like to find a file "findfile.txt" in MAIN, SUB1 and SUB2 folders.
say, i dont know how many subfolders available and also the names fo each folders. this is in my own server. nothing to do with user PC.
is it possible ? if so pls guide me
thanx in advance
look at the DIR function in VB help - it has an example of seraching in sub folders that will do the job with some minor changes ;)
Hi Geek,
thanx for ur valuable suggestion.
i was able to do it
thanx guys !!!
I just wish to add that, if you go on FSO way, you need to set the reference first. I got stuck few minutes looking for the right reference, so I though it might be relevant add this comment.Quote:
Originally posted by James Stanich
Or if you are still interested in the FSO way :
To do it, just go on Project / References and select the "Microsoft Scripting Runtime" one, which shall be located on something like: C:\Windows\System\scrrun.dll
When you pass the path to a file on your CD-Rom drive to the Dir() function but you have no CD inserted, it will bring up a run-time error 52 (filename or -number wrong).
So you better use one of the API functions ;)
I personally like the FindFirstFile() version best, because it works on all Windows versions and without any additional DLLs.
Flo
/edit: corrected the spelling ;)
hi,
u can use filesystemobject to check whether file exists or not
dim fs as new scripting.filesystemobject
msgbox fs.fileexists("c:\test.txt")
Looking all the methods mencioned in this thread, I think you can use one that never fails:
The "DIR" method can fail and the FSO or API method needs references.
Try this one:
VB Code:
Public Function FileExist(strFilename As String) As Boolean On Error Resume Next If Len(strFilename) <= 0 Then FileExist = False: Exit Function Dim ff As Long ff = FreeFile() Open strFilename For Input As #ff If Err Then FileExist = False Else FileExist = True End If Close #ff End Function
This method never fails (I had used it many times in A LOT of programs) and doesn't need any external declaration.
Plz tell me what do you think.
Andy
I know this is an old thread but I have to bring this up.
I have yet to find a way to determin if a folder exists but that it works on hidden folders. For instance they report that the folders like
C:\Windows\Fonts
C:\Documents and Settings\User\Cookies
C:\Documents and Settings\User\Recent
C:\Documents and Settings\User\SendTo
etc...
does anyone know a better way?
Ya, this is an old thread, but here is some code. You can parse the
Users directory from the Favorites dir. Then you will know that
the Cookies, etc. are in that folder too or use the second code
example to get the users dir.
VB Code:
Const CSIDL_DESKTOP = &H0 Const CSIDL_PROGRAMS = &H2 Const CSIDL_CONTROLS = &H3 Const CSIDL_PRINTERS = &H4 Const CSIDL_PERSONAL = &H5 Const CSIDL_FAVORITES = &H6 Const CSIDL_STARTUP = &H7 Const CSIDL_RECENT = &H8 Const CSIDL_SENDTO = &H9 Const CSIDL_BITBUCKET = &HA Const CSIDL_STARTMENU = &HB Const CSIDL_DESKTOPDIRECTORY = &H10 Const CSIDL_DRIVES = &H11 Const CSIDL_NETWORK = &H12 Const CSIDL_NETHOOD = &H13 Const CSIDL_FONTS = &H14 Const CSIDL_TEMPLATES = &H15 Const MAX_PATH = 260 Private Type SHI TEMID 'TAKE SPACE OUT cb As Long abID As Byte End Type Private Type ITEMIDLIST mkid As SHI TEMID 'TAKE SPACE OUT End Type Private Declare Function ShellAbout Lib "shell32.dll" Alias "ShellAboutA" (ByVal hWnd As Long, ByVal szApp As String, ByVal szOtherStuff As String, ByVal hIcon As Long) As Long Private Declare Function SHGetSpecialFolderLocation Lib "shell32.dll" (ByVal hwndOwner As Long, ByVal nFolder As Long, pidl As ITEMIDLIST) As Long Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long Private Sub Form_Load() 'KPD-Team 1998 'URL: [url]http://www.allapi.net/[/url] 'E-Mail: [email][email protected][/email] 'Show an about window ShellAbout Me.hWnd, App.Title, "Created by the KPD-Team 1999", ByVal 0& 'Set the graphical mode to persistent Me.AutoRedraw = True 'Print the folders to the form Me.Print "Start menu folder: " + GetSpecialfolder(CSIDL_STARTMENU) Me.Print "Favorites folder: " + GetSpecialfolder(CSIDL_FAVORITES) Me.Print "Programs folder: " + GetSpecialfolder(CSIDL_PROGRAMS) Me.Print "Desktop folder: " + GetSpecialfolder(CSIDL_DESKTOP) End Sub Private Function GetSpecialfolder(CSIDL As Long) As String Dim r As Long Dim IDL As ITEMIDLIST 'Get the special folder r = SHGetSpecialFolderLocation(100, CSIDL, IDL) If r = NOERROR Then 'Create a buffer Path$ = Space$(512) 'Get the path from the IDList r = SHGetPathFromIDList(ByVal IDL.mkid.cb, ByVal Path$) 'Remove the unnecessary chr$(0)'s GetSpecialfolder = Left$(Path, InStr(Path, Chr$(0)) - 1) Exit Function End If GetSpecialfolder = "" End FunctionVB Code:
Private Const TOKEN_QUERY = (&H8) Private Declare Function GetAllUsersProfileDirectory Lib "userenv.dll" Alias "GetAllUsersProfileDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean Private Declare Function GetDefaultUserProfileDirectory Lib "userenv.dll" Alias "GetDefaultUserProfileDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean Private Declare Function GetProfilesDirectory Lib "userenv.dll" Alias "GetProfilesDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean Private Declare Function GetUserProfileDirectory Lib "userenv.dll" Alias "GetUserProfileDirectoryA" (ByVal hToken As Long, ByVal lpProfileDir As String, lpcchSize As Long) As Boolean Private Declare Function GetCurrentProcess Lib "kernel32" () As Long Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long Private Sub Form_Load() 'KPD-Team 2000 'URL: [url]http://www.allapi.net/[/url] 'E-Mail: [email][email protected][/email] Dim sBuffer As String, Ret As Long, hToken As Long 'set the graphics mode of this form to 'persistent' Me.AutoRedraw = True 'create a string buffer sBuffer = String(255, 0) 'retrieve the all users profile directory GetAllUsersProfileDirectory sBuffer, 255 'show the result Me.Print StripTerminator(sBuffer) 'create a string buffer sBuffer = String(255, 0) 'retrieve the user profile directory GetDefaultUserProfileDirectory sBuffer, 255 'show the result Me.Print StripTerminator(sBuffer) 'create a string buffer sBuffer = String(255, 0) 'retrieve the profiles directory GetProfilesDirectory sBuffer, 255 'show the result Me.Print StripTerminator(sBuffer) 'create a string buffer sBuffer = String(255, 0) 'open the token of the current process OpenProcessToken GetCurrentProcess, TOKEN_QUERY, hToken 'retrieve this users profile directory GetUserProfileDirectory hToken, sBuffer, 255 'show the result Me.Print StripTerminator(sBuffer) End Sub 'strips off the trailing Chr$(0)'s Function StripTerminator(sInput As String) As String Dim ZeroPos As Long ZeroPos = InStr(1, sInput, Chr$(0)) If ZeroPos > 0 Then StripTerminator = Left$(sInput, ZeroPos - 1) Else StripTerminator = sInput End If End Function
that is ok, but I dont need to find the path for the special folders I need to determin if a folder exists or not. I just wrote those as example because they are hidden.
actually..... the FSO method works....
so..if the original post author is here they can 'resolve' this ...