Opening an existing file
<%
Const File_OpenForReading = 1
Const File_OpenForWriting = 2
Const File_OpenForAppending = 8
Function File_OpenExisting( strPath, nAccess )
' strPath = the path to file
' nAccess should be one of the constants above
On Error Resume Next
Dim objFileObj
Dim objFile
Set objFileObj = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFileObj.OpenTextFile( strPath, nAccess, False, False )
If Err = 0 Then
Set File_OpenExisting = objFile
Else
Set File_OpenExisting = Nothing
End If
End Function
%>
The function returns a File object if successful otherwise Nothing.
Use it like this:
<%
Dim oFile
Set oFile = File_OpenExisting( "c:\test.log", File_OpenForReading )
If oFile Is Nothing Then
Response.Write "Not existing"
Else
Response.Write "Existing"
'Here we can start reading from it
End If
%>
If you don't know the exact path to the file ( like c:\www\hello.txt ) - you might just know the file is located under the /files/ subdirectory at your webhost then you need to convert the path using Server.MapPath. Check out our String functions section for examples.
Closing a file in ASP
<%
Dim oFile
Set oFile = File_OpenExisting( "c:\test.log", File_OpenForReading )
If oFile Is Nothing Then
Response.Write "Not existing"
Else
Response.Write "Existing"
'Here we can start reading from it
End If
oFile.Close
'ASP Code continues...
%>
Open or create textfile with ASP
Create a new Blank file if it doesn't exists
<%
Const File_OpenForReading = 1
Const File_OpenForWriting = 2
Const File_OpenForAppending = 8
Function File_OpenExistingOrCreate( strPath, nAccess )
' strPath = the path to file
' nAccess should be one of the constants above
On Error Resume Next
Dim objFileObj
Dim objFile
Set objFileObj = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFileObj.OpenTextFile( strPath, nAccess, True, False )
If Err = 0 Then
Set File_OpenExistingOrCreate = objFile
Else
Set File_OpenExistingOrCreate = Nothing
End If
End Function
%>
The function returns a File object if successful otherwise Nothing.
Use it like this:
<%
Dim oFile
Set oFile = File_OpenExistingOrCreate( "c:\test.log", File_OpenForWriting )
If oFile Is Nothing Then
Response.Write "Not existing"
Else
Response.Write "Existing"
'Here we can start writing to it
End If
%>
If you don't know the exact path to the file ( like c:\www\hello.txt ) - you might just know the file is located under the /files/ subdirectory at your webhost then you need to convert the path using Server.MapPath. Check out our String functions section for examples.