Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Reading Files in ASP and How to Search for a particular text in all files in a specific directory.

0.00/5 (No votes)
3 Jun 2004 1  
This article gives an introduction to the FileSystemObject using ASP, about how to create/modify/delete files, and a sample to find a particular string in all files in a specific folder.

Introduction

FileSystemObject provides access to a computer's file system. Some of the common tasks that can be performed using FileSystemObject are to check for a particular folder, drive, or file, and create/modify/delete files (if you have proper folder/file permissions).

Let's Start

To start with, following is the code which describes how to use the FileSystemObject to create a text file, and write some text:

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set a = fso.CreateTextFile("c:\testfile.txt", True)
    a.WriteLine("This is a test.")
    a.Close
    set a = nothing
    set fso = nothing 

You create an instance of FileSystemObject, and create a text file c:\testfile.txt, and write some text into it. The second method to create a text file is by using OpenTextFile method of FileSystemObject object with ForWriting flag.

    Const ForWriting = 2
    Set a = fsoOpenTextFile ("c:\testfile.txt", ForWriting ,True)

You can use WriteLine or Write method to write the contents. The basic difference between WriteLine and Write is, Write writes with a trailing newline character, and WriteLine without a trailing newline character. You can use WriteBlankLines method to write blank lines.

For example, to write three blank lines, you could use the following:

    a.WriteBlankLines(3)

Following are the modes, by which files can be opened:

  • ForReading (Constant value - 1) - Open a file for reading only.
  • ForWriting (Constant value - 2) - Open a file for writing.
  • ForAppending (Constant value - 8) - Open a file and write to the end of the file.

For example, to declare constant for reading:

    Const ForReading = 1

Let's see an example to read a text file:

    dim s
    Const ForReading = 1
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set a = fso.OpenTextFile("c:\testfile.txt", ForReading)
    s = ts.ReadLine
    a.Close
    set a = nothing
    set fso = nothing 
    Response.Write "File Content : '" & s & "'"

For reading contents from the file, following methods will be used:

To read a specified number of characters from a file, use Read method. To read an entire line (all except the newline character), use ReadLine method. To read the entire contents of a text file, use ReadAll method.

Let's have a quick look at how to move, copy and delete files:

  1. To move a file, use File.Move or FileSystemObject.MoveFile.
  2. To copy a file, use File.Copy or FileSystemObject.CopyFile.
  3. To delete a file, use File.Delete or FileSystemObject.DeleteFile.

Following example will show as to how to manipulate a file using File methods:

   Dim fso
   
   Set fso = CreateObject("Scripting.FileSystemObject")
      
   'Move a File

   Set f2 = fso.GetFile("c:\testfile.txt")
   f2.Move ("c:\temp\testfile.txt")    ' Move the file to \temp directory.

   
   'Copy file to \temp.

   f2.Copy ("c:\temp\testfile.txt")
   
   'Delete File 

   Set f2 = fso.GetFile("c:\tmp\testfile.txt")
   f2.Delete

Following example will show as to how to manipulate a file using FileSystemObject methods:

   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
      
   'Move a File

   Set f2 = fso.GetFile("c:\testfile.txt")
   fso.MoveFile("source_file", "destination");
   
   'Copy file to c:\temp folder

   fso.CopyFile "c:\testfile.txt", "c:\temp\"
   
   'Delete File 

   fso.DeleteFile "c:\testfile.txt"

Sample: How to search for a particular string in a specific folder in all files

Form to accept the string will be as follows:

    <FORM METHOD=POST id=form1 action="searchresult.asp" 
                           name=form1 onsubmit="return Check();">
      Enter text to search for:
      <INPUT TYPE=TEXT NAME=TextToSearch>
      <P>
      <INPUT TYPE=SUBMIT VALUE="Begin Search!" id=SUBMIT1 name=SUBMIT1>
    </FORM>

To search for a string in particular folder, following is the code: (searchresults.asp)

    'Search Text

    Dim strtextToSearch
    strtextToSearch = Request("TextToSearch")

    'Now, we want to search all of the files

    Dim fso

    'Constant to read

    Const ForReading = 1
    Set fso = Server.CreateObject("Scripting.FileSystemObject")

    'Specify the folder path to search.

    Dim FolderToSearch
    FolderToSearch = "D:\temp"
    
    'Proceed if folder exists

    if fso.FolderExists(FolderToSearch) then 
        
        Dim objFolder    
        Set objFolder = fso.GetFolder(FolderToSearch)
        
        Dim objFile, objTextStream, strFileContents, bolFileFound
        bolFileFound = False

        Dim FilesCounter
        FilesCounter = 0 'Total files found


        For Each objFile in objFolder.Files
            Set objTextStream = fso.OpenTextFile(objFile.Path,ForReading)
            'Read the content

            strFileContents = objTextStream.ReadAll
            If InStr(1,strFileContents,strtextToSearch,1) then
               Response.Write objFile.Name & "<br>"
               FilesCounter = FilesCounter + 1
            End If
            objTextStream.Close
        Next

        if FilesCounter = 0 then 
            Response.Write "Sorry, No matches found."
        else
            Response.Write "Total files found : " & FilesCounter
        end if    
        
        'Destroy the objects

        Set objTextStream = Nothing
        Set objFolder = Nothing

    else
        Response.Write "Sorry, invalid folder name"
    end if
    Set fso = Nothing

Summary

This article gives you a brief introduction about FileSystemObject, how to create/delete text files, and an example of how to use FileSystemObject to search for a particular string in all files located in a specific folder.

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here