Click to See Complete Forum and Search --> : Classic VB - How can I check if a file exists?
sciguyryan
May 31st, 2005, 05:52 AM
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:
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:
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).
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
RobDog888
May 23rd, 2006, 01:03 AM
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 ...
'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
'Usage:
'Behind Form1:
Option Explicit
Private Sub Form_Load()
MsgBox FileExists("C:\Test.txt") 'True :D
End Sub Enjoy!
VB/Office Guru™ http://www.vbforums.com/attachment.php?attachmentid=38679®
RhinoBull
May 26th, 2006, 07:57 PM
There is always a FileSystemObject (scripting library).
Coinsidentally (with what Rob has posted) it also has FileExists function that returns boolean:
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
MarkT
Dec 17th, 2008, 02:12 PM
I have always found the GetAttr function to be a good quick way to check the existence of a file.
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
dee-u
Dec 18th, 2008, 06:42 AM
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.
'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:
'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
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.