简体   繁体   中英

How can I open an HTML file as a text file to read the code using VBScript?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM