Sunday, March 22, 2009

Classic ASP: dump text file contents into array

The code below is reading text file and putting its lines into array.
After the code is executed, each item of the array will be one
line of the text file.


<%

Function ReadTextFile(strFilePath)

 Dim objFSO, objFile, strAllFile

 Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

 Set objFile = objFSO.OpenTextFile(strFilePath)

 strAllFile = ""

 If Not(objFile.AtEndOfStream) Then

  strAllFile = objFile.ReadAll

 End If

 objFile.Close

 Set objFile = Nothing

 Set objFSO = Nothing

 

 strAllFile = Replace(strAllFile, Chr(13)&Chr(10), Chr(13))

 strAllFile = Replace(strAllFile, Chr(10)&Chr(13), Chr(13))

 ReadTextFile = Split(strAllFile, Chr(13))

End Function



'usage

Const FILE_NAME="myfile.txt"

Dim arrLines, x, curLine

Response.Write("reading file: " & FILE_NAME & "...<br />")

arrLines = ReadTextFile(Server.MapPath(FILE_NAME))

Response.Write("amount of lines: " & (UBound(arrLines)+1) & "<br />")

Response.Write("file contents:<hr />")

For x=0 To UBound(arrLines)

 curLine = arrLines(x)

 Response.Write("Line #" & (x+1) & " " & Server.HTMLEncode(curLine) & "<br />")

Next

Response.Write("<hr />")

%>



Source: http://forums.aspfree.com/

No comments:

Post a Comment