简体   繁体   English

如何打开HTML文件作为文本文件以使用VBScript读取代码?

[英]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. 我有很多HTML页面,需要在其上更改几行相同的文本。 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? 如何打开HTML文件,读取组成页面的代码并查找并替换其中的文本? 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文件呢?

html files ARE text files, just open them like you would any other text file. html文件是文本文件,只需像打开其他任何文本文件一样打开它们即可。

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. 糟糕,对不起,我想我在评论中把vbscript与常规的Visual Basic混在一起了。

In vbscript, the regular approach would be to use the FileSystemObject, like Helen suggested. 在vbscript中,常规方法是使用FileSystemObject,就像Helen建议的那样。

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). HTML文件是文本文件,因此您可以按照与读取任何其他文本文件相同的方式来读取它们(例如,使用FileSystemObject对象)。

Now, is there a way for my script to open all .html files in a specified folder without knowing their names? 现在,有没有一种方法可以让我的脚本在不知道其名称的情况下打开指定文件夹中的所有.html文件?

You can enumerate the Folder.Files collection and check the file extension, like this: 您可以枚举Folder.Files集合并检查文件扩展名,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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