
December 23rd, 2005, 03:24 PM
|
 |
Moderator From Beyond
|
|
Join Date: Sep 2004
Location: Israel
|
|
Classic ASP/vbscript: write into specific line in text file
The code below get file path and string to be written, and
writes the string into the specified file, in the given line
number.
The text is "pushed" in that line, pushing all
other lines below.
If the text file does not exist, it's being created and the
text written as the first line.
If the line number exceeds the amount of lines in the file,
the text is written as the last line.
Happy Programming!
Code:
Sub WriteToFile(strFilePath, strData, iLineNumber)
Dim objFSO, objFile, arrLines
Dim strAllFile, x
Set objFSO=Server.CreateObject("Scripting.FileSystemObject")
strAllFile=""
If objFSO.FileExists(strFilePath) Then
Set objFile=objFSO.OpenTextFile(strFilePath)
If Not(objFile.AtEndOfStream) Then
strAllFile = objFile.ReadAll
End If
objFile.Close
End If
arrLines = Split(strAllFile, VBCrLf)
Set objFile=objFSO.CreateTextFile(strFilePath)
For x=0 To UBound(arrLines)
If (iLineNumber-1)=x Then objFile.WriteLine(strData)
objFile.WriteLine(arrLines(x))
Next
If iLineNumber>=UBound(arrLines) Then objFile.WriteLine(strData)
objFile.Close
Set objFile=Nothing
Set objFSO=Nothing
End Sub
'usage:
Call WriteToFile(Server.MapPath("log.txt"), Request.ServerVariables("REMOTE_ADDR"), 5)
|