回想一下,OpenTextFile方法返回一个TextStream对象,它是FSO模型中的另外一个对象。TextStream对象揭示了操作文件内容的方法,比如写、读一行、跳过一行。VB常量vbcrlf产生一个换行符。
在OpentextFile的命令参数中定义了TRUE,这就告诉了系统,如果文件不存在,就创建它。如果文件不存在,并且没有定义TRUE参数,就会出错。
现在转到目录c: emp,打开test.txt,你可以看到如下的信息:
| User's name User's home page User's email |
| < % ' create the fso object set fso = Server.Createobject("Scripting.FileSystemObject") path = "c: emp est.txt" ' open the file set file = fso.opentextfile(path, 1) < -- For reading |
| do until file.AtEndOfStream Response.write("Name: " & file.ReadLine & " ") Response.write("Home Page: " & file.ReadLine & " ") Response.write("Email: " & file.ReadLine & "< p>") loop ' close and clean up file.close set file = nothing set fso = nothing %> |
| Server object error 'ASP 0177 : 800a003e' |
| Dim objFolder Dim strSearchText Dim objFSO strSearchText = Request.Form("SearchText") < -- The search string ' create the FSO and Folder objects Set fso = Server.CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.GetFolder(Server.MapPath("/")) Search objFolder |
| Function Search(objFolder) Dim objSubFolder 'loop through every file in the current folder For Each objFile in objFolder.Files Set objTextStream = objFSO.OpenTextFile(objFile.Path,1) < -- For Reading 'read the file's contents into a variable strFileContents = objTextStream.ReadAll 'if the search string is in the file, then write a link ' to the file If InStr(1, strFileContents, strSearchText, 1) then Response.Write "< A HREF=""/" & objFile.Name & _ """>" & objFile.Name & "< /A>< BR>" bolFileFound = True End If objTextStream.Close Next 'Here's the recursion part - for each ' subfolder in this directory, run the Search function again For Each objSubFolder in objFolder.SubFolders Search objSubFolder Next End Function |