views:

124

answers:

2

I have a lot of HTML pages that need the same few lines of text changed on them. To reduce the time it will take to manually open each one in Notepad and find the text and replace it with the new text, I would like to create a script to do this for me.

How can I open an HTML file, read the code the makes up the page and find & replace the text in it? I know how to open, read, find/replace, write, close a text file, but is there a way to do it with HTML files?

+3  A: 

html files ARE text files, just open them like you would any other text file.

so instead of:

Dim fileReader As New System.IO.StreamReader("c:\file.txt")

just do

Dim fileReader As New System.IO.StreamReader("c:\file.html")

In generall, text readers in programming languages don't really care about the extension of a file as long as it contains text.

[edit]

woops, sorry, i guess I got vbscript mixed up with regular visual basic in the comment.

In vbscript, the regular approach would be to use the FileSystemObject, like Helen suggested.

Zenon
Oh wow, why didn't I think of that? Now, is there a way for my script to open all .html files in a specified folder without knowing their names?
wahle509
Those examples do not include VBScript.
wahle509
+1  A: 

HTML files are text files, so you can read them in the same way you would read any other text files (for example, using the FileSystemObject object).

Now, is there a way for my script to open all .html files in a specified folder without knowing their names?

You can enumerate the Folder.Files collection and check the file extension, like this:

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0

Dim oFSO, oFolder, oFile, oTextStream, strText

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:\MyFolder")

For Each oFile In oFolder.Files
  If LCase(oFSO.GetExtensionName(oFile.Name)) = "html" Then

    Set oTextStream = oFile.OpenAsTextStream(ForReading, TristateUseDefault)
    strText = oTextStream.ReadAll
    oTextStream.Close

    ' Do something with strText '

    Set oTextStream = oFile.OpenAsTextStream(ForWriting, TristateUseDefault)
    oTextStream.Write strText
    oTextStream.Close

  End If
Next
Helen