-
May 31st, 2005, 04:52 AM
#1
Thread Starter
Frenzied Member
Classic VB - How can I check if a file exists?
Visual basic has a built-in function called Dir which lists files for you, based on options you specify.
If you specify a full filename (and path) it will return the filename if the file exists. If the specified file doesn't
exist, an empty string "" will be returned.
To find the file C:\Test.txt you would do the following:
VB Code:
If Dir("C:\Test.txt") <> "" Then
Msgbox "File exists"
Else
Msgbox "File does not exist"
End If
If the file has special attributes (eg: is Hidden) you need to specify this too, eg:
VB Code:
If Dir("C:\Test.txt", vbHidden) <> "" Then
Msgbox "File exists"
End If
Here is a function you can use which returns True if the specified file exists (or False if it doesn't).
VB Code:
Private Function CheckPath(strPath As String) As Boolean
If Dir$(strPath) <> "" Then
CheckPath = True
Else
CheckPath = False
End If
End Function
Just call the above function with the path of the file to check as its parameter.
Cheers,
RyanJ
Last edited by si_the_geek; Jul 24th, 2007 at 05:14 PM.
Reason: added explanation, tidied up, and corrected code
-
May 23rd, 2006, 12:03 AM
#2
Re: Classic VB - How can I check if a file exists?
For the ultimate reliable way to determine if a file exists, any file attributes like vbHidden, vbSystem, or any combination of any other file attributes will not affect the results ...
VB Code:
'In a standard Module: Module1.bas
Option Explicit
Private Const OF_EXIST As Long = &H4000
Private Const OFS_MAXPATHNAME As Long = 128
Private Const HFILE_ERROR As Long = -1
Private Type OFSTRUCT
cBytes As Byte
fFixedDisk As Byte
nErrCode As Integer
Reserved1 As Integer
Reserved2 As Integer
szPathName(OFS_MAXPATHNAME) As Byte
End Type
Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, _
lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
Public Function FileExists(ByVal Fname As String) As Boolean
Dim lRetVal As Long
Dim OfSt As OFSTRUCT
lRetVal = OpenFile(Fname, OfSt, OF_EXIST)
If lRetVal <> HFILE_ERROR Then
FileExists = True
Else
FileExists = False
End If
End Function
VB Code:
'Usage:
'Behind Form1:
Option Explicit
Private Sub Form_Load()
MsgBox FileExists("C:\Test.txt") 'True :D
End Sub
Enjoy!
VB/Office Guru™ ®
Last edited by si_the_geek; May 23rd, 2006 at 05:29 AM.
-
May 26th, 2006, 06:57 PM
#3
Re: Classic VB - How can I check if a file exists?
There is always a FileSystemObject (scripting library).
Coinsidentally (with what Rob has posted) it also has FileExists function that returns boolean:
VB Code:
Private Sub Command1_Click()
'============================
Dim fso As FileSystemObject
Dim sFilePath As String
Set fso = New FileSystemObject
sFilePath = "c:\test.txt"
If fso.FileExists(sFilePath) Then
MsgBox "File Exist."
Else
MsgBox "File Doesn't Exist."
End If
End Sub
Last edited by si_the_geek; May 27th, 2006 at 06:08 PM.
-
Dec 17th, 2008, 02:12 PM
#4
Re: Classic VB - How can I check if a file exists?
I have always found the GetAttr function to be a good quick way to check the existence of a file.
Code:
Private Sub Command1_Click()
Debug.Print FileExists("C:\somefile.txt")
End Sub
Private Function FileExists(ByVal sFileName As String) As Boolean
Dim intReturn As Integer
On Error GoTo FileExists_Error
intReturn = GetAttr(sFileName)
FileExists = True
Exit Function
FileExists_Error:
FileExists = False
End Function
-
Dec 18th, 2008, 06:42 AM
#5
Re: Classic VB - How can I check if a file exists?
We can also utilize the API's FindFirstFile and FindNextFile to determine the existence of a file or a folder, it can also support wildcard searches which I demonstrate here.
vb Code:
'In a standard Module
Option Explicit
Public Const MAX_PATH As Long = 260
Private Const ERROR_NO_MORE_FILES As Long = 18&
Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
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 * MAX_PATH
cAlternate As String * 14
End Type
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" ( _
ByVal lpFileName As String, _
lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindClose Lib "kernel32" ( _
ByVal hFindFile As Long) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" ( _
ByVal hFindFile As Long, _
lpFindFileData As WIN32_FIND_DATA) As Long
Public Function FileExists(ByVal sFile As String) As Boolean
Dim lpFindFileData As WIN32_FIND_DATA
Dim lFileHandle As Long
Dim lRet As Long
Dim sTemp As String
Dim sFileExtension As String
Dim sFileName As String
Dim sFileData() As String
Dim sFileToCompare As String
If IsDirectory(sFile) = True Then
sFile = AddSlash(sFile) & "*.*"
End If
If InStr(sFile, ".") > 0 Then
sFileToCompare = GetFileTitle(sFile)
sFileData = Split(sFileToCompare, ".")
sFileName = sFileData(0)
sFileExtension = sFileData(1)
Else
Exit Function
End If
' get a file handle
lFileHandle = FindFirstFile(sFile, lpFindFileData)
If lFileHandle <> -1 Then
If sFileName = "*" Or sFileExtension = "*" Then
FileExists = True
Else
Do Until lRet = ERROR_NO_MORE_FILES
' if it is a file
If (lpFindFileData.dwFileAttributes And FILE_ATTRIBUTE_NORMAL) = vbNormal Then
sTemp = StrConv(RemoveNull(lpFindFileData.cFileName), vbProperCase)
'remove LCase$ if you want the search to be case sensitive
If LCase$(sTemp) = LCase$(sFileToCompare) Then
FileExists = True ' file found
Exit Do
End If
End If
'based on the file handle iterate through all files and dirs
lRet = FindNextFile(lFileHandle, lpFindFileData)
If lRet = 0 Then Exit Do
Loop
End If
End If
' close the file handle
lRet = FindClose(lFileHandle)
End Function
Private Function IsDirectory(ByVal sFile As String) As Boolean
On Error Resume Next
IsDirectory = ((GetAttr(sFile) And vbDirectory) = vbDirectory)
End Function
Private Function RemoveNull(ByVal strString As String) As String
Dim intZeroPos As Integer
intZeroPos = InStr(strString, Chr$(0))
If intZeroPos > 0 Then
RemoveNull = Left$(strString, intZeroPos - 1)
Else
RemoveNull = strString
End If
End Function
Public Function GetFileTitle(ByVal sFileName As String) As String
GetFileTitle = Right$(sFileName, Len(sFileName) - InStrRev(sFileName, "\"))
End Function
Public Function AddSlash(ByVal strDirectory As String) As String
If InStrRev(strDirectory, "\") <> Len(strDirectory) Then
strDirectory = strDirectory + "\"
End If
AddSlash = strDirectory
End Function
Sample Usage:
VB Code:
'specific file
If FileExists("C:\WINDOWS\system32\progman.exe") Then
MsgBox "Existing!"
Else
MsgBox "Not Existing!"
End If
'check existence of folder
If FileExists("C:\Program Files") Then
MsgBox "Existing!"
Else
MsgBox "Not Existing!"
End If
'wildcard search1
If FileExists("C:\WINDOWS\system32\pschdprf.*") Then
MsgBox "Existing!"
Else
MsgBox "Not Existing!"
End If
'wildcard search2
If FileExists("C:\WINDOWS\system32\*.dll") Then
MsgBox "Existing!"
Else
MsgBox "Not Existing!"
End If
'wildcard search3
If FileExists("C:\WINDOWS\*.*") Then
MsgBox "Existing!"
Else
MsgBox "Not Existing!"
End If
Last edited by dee-u; Jan 7th, 2009 at 11:02 PM.
Reason: Added support for searching folders and wildcard searches
-
May 22nd, 2015, 02:48 PM
#6
Member
Re: Classic VB - How can I check if a file exists?
Just a tip... don't use the dir function to check if files exist.
It will muck up any other functions you have which use dir in a loop.
David
-
May 30th, 2015, 10:21 AM
#7
Re: Classic VB - How can I check if a file exists?
Here's yet another reason to avoid Dir:
Originally Posted by Bonnie West
Note that the Dir function may return a filename when an empty or null string is passed to it. The GetAttr function is better (and faster) in this regard:
Code:
Public Function FileExists(ByRef sFileName As String) As Boolean
On Error Resume Next
FileExists = (GetAttr(sFileName) And vbDirectory) <> vbDirectory
On Error GoTo 0
End Function
The Unicode version of the underlying API is even faster ( on NT-based OSs):
Code:
Private Declare Function GetFileAttributesW Lib "kernel32.dll" (ByVal lpFileName As Long) As Long
Public Function FileExists(ByRef sFileName As String) As Boolean
Const ERROR_SHARING_VIOLATION = 32&
Select Case (GetFileAttributesW(StrPtr(sFileName)) And vbDirectory) = 0&
Case True: FileExists = True
Case Else: FileExists = Err.LastDllError = ERROR_SHARING_VIOLATION
End Select
End Function
References:
Last edited by Bonnie West; Feb 7th, 2016 at 03:53 AM.
On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
Declare Sub CrashVB Lib "msvbvm60" (Optional DontPassMe As Any)
-
Nov 3rd, 2024, 05:52 PM
#8
Fanatic Member
Re: Classic VB - How can I check if a file exists?
The problem with this is that it returns True for "VB6.exe".
Why? Because the app "VB6.exe" may be in your directory, but in fact you just messed up something.
Now pass this assumingly existing "path" on to an ActiveX exe, assuming the file really exists and BAMM.
Your ActiveX might be in a different path than your exe, and finally you notice that the function betrayed you.
Praising a function's speed without applying error checks to compensate for such problems is not fair.
-
Nov 4th, 2024, 02:50 AM
#9
Re: Classic VB - How can I check if a file exists?
Can you tell to which method you are referring?
And elaborate on what you’re testing?
-
Nov 4th, 2024, 03:44 AM
#10
Fanatic Member
Re: Classic VB - How can I check if a file exists?
My method is not good.
What I do now if testing if "" is included in the path. If not, I return FAlse.
I was heavily frustrated when I noticed this flaw after using my FileExists method for 24 years, and all suggestions showed the same behaviour and nobody pointed out this problem.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|