Send me more information about:

ASP Script, Write lines in a text file

Function to return the count of lines within a text file

Many websites use summaries to list out articles and news items, frequently chopping off the first sentence or offering the non too attractive ... trailing characters. Not to be outdone we were asked to display the first paragraph from a recordset. The following function offers this feature:


VBscript Function


Function LineCnt(strFile)

   'Create a File System Object
   Dim fsobject
   Set fsobject = CreateObject("Scripting.FileSystemObject")

   Dim TheFile
   Set TheFile = fsobject.OpenTextFile(strFile, 1, False)

   Dim CntlInes
   Do While Not TheFile.AtEndOfStream
         CntlInes = CntlInes + 1

   'Return the file's line count
   LineCnt = CntlInes

   Set TheFile = Nothing
   Set fsobject = Nothing

End Function



Deploying the function





In this function we use one the common scripting objects FileSystemObject which allows us to reference external files such as txt or csv files. Once we have initiated an instance of the object we then have to "open" the file for whatever we want to do with it, in this case "read" the file ([name],1,false) the 1 in this case.


We then loop through each line using the "AtEndOfStream" command to exit the loop whilst incrementing the loop a line at a time "CntlInes = CntlInes + 1 " before finally creating a dimensioned variable for use on the page.


Finally we always close and set the object to nothing to tidy up any open connections otherwise we run the risk (if we use the function over again) of creating non-closed connections to the same file and eventually reducing the server resources available.


Mark Lawson July 2007