|
How to Check if a File Exists |
|
|
|
|
Source Codes -
Visual Basic
|
|
Written by Thomas Kaloyani
|
An efficient way to check if a file exists or not, regardless of the file attributes, is using the OpenFile API.
The following code shows how to make the API call.
Usage:
if FileExists("C:\MyFile.txt") then
Debug.Print "Exists"
else
Debug.Print "Don't Exists"
end if
Declarations:
Private Const OF_EXIST As Long = &H4000
Private Const OF_ERROR As Long = -1
Private Const OFS_MAXPATHNAME As Long = 128
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
Code:
Private Function FileExists(ByVal sFile As String) As Boolean
Dim lRetVal As Long
Dim of As OFSTRUCT
lRetVal = OpenFile(sFile, of, OF_EXIST)
If lRetVal <> OF_ERROR Then
FileExists = True
Else
FileExists = False
End If
End Function
Thomas is an experienced Visual Basic developer, with expertise of 7+ years developing especially financial applications. His main IT skills are VB, SQL, Crystal Reports - should you need a Visual Basic developer for your projects feel free to contact Thomas through his personal website www.Kaloyani.com or through VBprofs.com - the newest Visual Basic and VB.NET resources portal.
Source: www.VBprofs.com
|