Use the FileToArray Function to Read a Text File Into an Array


Opening text files is a common scripting task. Through the Microsoft Scripting Runtime Library's FileSystemObject object, you can access the TextStream object, which provides methods and properties for working with text files. Opening text files usually entails a series of steps, such as

  1. Create an instance of the FileSystemObject object.
  2. Use FileSystemObject's OpenTextFile method to create a TextStream object.
  3. Use the TextStream object's methods to read the contents of the file.
  4. Close the file.

Although these steps aren't difficult to implement, I find it convenient to retrieve a text file into an array, so I created the FileToArray function. Reading a file into an array has its advantages. You can use a For Each...Next statement to iterate through all the lines or use an array index to access just one line. You can even iterate through a file multiple times without having to close it and open it again.

Listing 1 shows the FileToArray function. The function first declares its return value to be an empty, single-element array by using VBScript's Split function, as callout A in Listing 1 shows. That way, the function always returns an array, even if an error occurs.

Next, FileToArray creates a FileSystemObject instance and uses the FileExists method to check whether the specified file exists. If the file doesn't exist, the function returns an empty array and ends. If the file exists, the function uses the On Error Resume Next statement to disable VBScript's error handler and uses FileSystemObject's OpenTextFile method to create a TextStream object.

Provided that the OpenTextFile method succeeds, the function uses TextStream's ReadAll method to retrieve the file's contents into a single string variable, then closes the file. Finally, the function uses the Split function to return the file's contents as an array, as callout B in Listing 1 shows.

To use the FileToArray function, you add the code that Listing 1 shows to your script, then call the function using the syntax

FileToArray(strFile, blnUNICODE)

The strFile parameter specifies the name of the file. The blnUNICODE parameter is a Boolean value that specifies whether (True value) or not (False value) the file is in Unicode format. Listing 2 shows an example of how you might call FileToArray in a script. This VBScript code displays the contents of the boot.ini file. Note that the FileToArray function will likely perform poorly on very large text files because it relies on TextStream's ReadAll method to read the entire file into memory at once.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.