<%
' *** Inline Code Version ***
' If you need to do other things to the file once you verify its
' existance, then this is probably the way to go. That way
' you'll be able to reuse the same FileSystemObject before
' you close it.
Dim objFSO ' FileSystemObject variable.
Dim strFileThatExists ' The name of the file that exists.
Dim strFileThatDoesnt ' The name of the file that doesn't exist.
strFileThatExists = "file_exists.asp"
strFileThatDoesnt = "file_doesnt.asp"
' Create an instance of the FSO in order to access the file system.
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
' The FileExists method expects a fully qualified path and
' filename. I've specified relative file names above. In order
' to get the full path we make a call to Server.MapPath to give us
' the corresponding physical path to the file on the server's file
' system.
%>
<p>
<strong>Inline Code Version:</strong>
</p>
<p>
Checking to see if "<%= strFileThatExists %>" exists:
<b><%= objFSO.FileExists(Server.MapPath(strFileThatExists)) %></b>
</p>
<p>
Checking to see if "<%= strFileThatDoesnt %>" exists:
<b><%= objFSO.FileExists(Server.MapPath(strFileThatDoesnt)) %></b>
</p>
<%
Set objFSO = Nothing
' *** Function Version ***
' As I mentioned above, I didn't wrap the above version in a
' function because after you check if a file exists, you'll
' probably want to do something with it. If that's not the case,
' this function will just check if a file exists and return "True"
' if it does and "False" if it doesn't.
Function DoesFileExist(ByVal strFileName)
' You'll notice I use ByVal when passing in strFileName.
' That's because I play around with its value inside the
' function and don't want any changes I make affecting
' its value outside the function.
Dim objFSO
' If we don't have a full path starting with a drive letter
' then we run the path through Server.MapPath().
If InStr(strFileName, ":") = 0 Then
strFileName = Server.MapPath(strFileName)
End If
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
DoesFileExist = objFSO.FileExists(strFileName)
Set objFSO = Nothing
End Function
%>
<p>
<strong>Function Version:</strong>
</p>
<p>
Checking to see if "<%= strFileThatExists %>" exists:
<b><%= DoesFileExist(strFileThatExists) %></b>
</p>
<p>
Checking to see if "<%= strFileThatDoesnt %>" exists:
<b><%= DoesFileExist(strFileThatDoesnt) %></b>
</p>