|
-
Jun 3rd, 2003, 11:37 AM
#1
Thread Starter
Fanatic Member
checking if a file exists
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?
-
Jun 3rd, 2003, 11:48 AM
#2
Re: checking if a file exists
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?
It's a little easier than that:
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!"
-
Jun 3rd, 2003, 11:55 AM
#3
Frenzied Member
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
-
Jun 3rd, 2003, 12:30 PM
#4
PowerPoster
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.
-
Jun 3rd, 2003, 01:16 PM
#5
Addicted Member
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
-
Jun 3rd, 2003, 01:53 PM
#6
PowerPoster
Well
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
Remaining quiet down here !!!
BRAD HAS GIVEN ME THE ULTIMATIVE. I have chosen to stay....
-
Jun 3rd, 2003, 02:17 PM
#7
Frenzied Member
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
-
Jun 13th, 2003, 04:17 AM
#8
Member
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
world is good..... people are bad...........but sometimes people are very good ! ! !
-
Jun 14th, 2003, 08:29 AM
#9
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
-
Jun 16th, 2003, 01:25 AM
#10
Member
Hi Geek,
thanx for ur valuable suggestion.
i was able to do it
thanx guys !!!
world is good..... people are bad...........but sometimes people are very good ! ! !
-
Aug 26th, 2003, 01:25 PM
#11
Lively Member
Re: Well
Originally posted by James Stanich
Or if you are still interested in the FSO way :
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.
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
--
Cauê Cavalheiro Machado Rego
-
Sep 1st, 2003, 08:33 AM
#12
Lively Member
-
Sep 1st, 2003, 09:09 AM
#13
Hyperactive Member
hi,
u can use filesystemobject to check whether file exists or not
dim fs as new scripting.filesystemobject
msgbox fs.fileexists("c:\test.txt")
-
Sep 1st, 2003, 02:55 PM
#14
Member
Look this
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
-
Sep 22nd, 2004, 04:11 PM
#15
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?
-
Sep 22nd, 2004, 04:48 PM
#16
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]
'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 Function
VB 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]
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
VB/Office Guru™ (AKA: Gangsta Yoda™ ®)
I dont answer coding questions via PM. Please post a thread in the appropriate forum. 
Microsoft MVP 2006-2011
Office Development FAQ (C#, VB.NET, VB 6, VBA)
Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
If a post has helped you then Please Rate it! 
• Reps & Rating Posts • VS.NET on Vista • Multiple .NET Framework Versions • Office Primary Interop Assemblies • VB/Office Guru™ Word SpellChecker™.NET • VB/Office Guru™ Word SpellChecker™ VB6 • VB.NET Attributes Ex. • Outlook Global Address List • API Viewer utility • .NET API Viewer Utility •
System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6 
-
Sep 22nd, 2004, 06:27 PM
#17
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.
-
Sep 22nd, 2004, 08:03 PM
#18
actually..... the FSO method works....
so..if the original post author is here they can 'resolve' this ...
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
|