日期:2011-10-13  浏览次数:20984 次

ASP本身不支持动态包含文件,现在的动态包含是通过FSO把被包含的文件合并到主文件里再运行。以下也有把形如<!--#includefile="filename.asp"-->的普通包含文件方式称作“传统引用”,用函数实现的动态包含文件称作“动态引用”。常见的程序如下:
Functioninclude(filename)
 Dimre,content,fso,f,aspStart,aspEnd
 
 setfso=CreateObject("Scripting.FileSystemObject")
 setf=fso.OpenTextFile(server.mappath(filename))
 content=f.ReadAll
 f.close
 setf=nothing
 setfso=nothing
 
 setre=newRegExp
 re.pattern="^s*="
 aspEnd=1
 aspStart=inStr(aspEnd,content,"<%")+2
 dowhileaspStart>aspEnd+1
 Response.writeMid(content,aspEnd,aspStart-aspEnd-2)
 aspEnd=inStr(aspStart,content,"%>")+2
 Execute(re.replace(Mid(content,aspStart,aspEnd-aspStart-2),"Response.Write"))
 aspStart=inStr(aspEnd,content,"<%")+2
 loop
 Response.writeMid(content,aspEnd)
 setre=nothing
EndFunction

使用范例:include("youinc.asp")

以上范例引自

但这处函数在处理补包含的文件中还有包含文件时就不灵了。我在以上函数的基础上改进出来如下函数,在被包含文件中还有普通的包含文件<!--#includefile="filename.asp"-->也可正常运行。

Functionincludeconvert(oRegExp,strFilename,strBlock)
 DimincStart,incEnd,match,oMatches,str,code
 '用提取ASP代码的相同方式提取出include部分的文件名,其余部分原样输出
 code=""
 incEnd=1
 incStart=InStr(incEnd,strBlock,"<!--#include")+13 '要找个目标字符串<!--#include正好是13个字符,所以要+13
 DoWhileincStart>incEnd+12 '两个引用间距最小就是连续的--><--#,incStart是从<!--#include起数13个字符,所以要比前一个incEnd要至少多13-1得到的>incEnd+12的条件
  str=Mid(strBlock,incEnd,incStart-incEnd-13)
  str=Replace(str,"""","""""") '把单个双引号换成两个双引号
  str=Replace(str,VbCr,"")
  str=Replace(str,VbLf,"")
  str=Replace(str,VbCrLf,"")
  code=code&VbCrLf&"Response.Write"""&str&""""
  incEnd=InStr(incStart,strBlock,"-->")+3
  oRegExp.pattern="(w+)=""([^""]+)""" '匹配file="filename.ext"或virtual="virtualname.ext",捕捉类型及文件名两个子串
  SetoMatches=oRegExp.Execute(Mid(strBlock,incStart,incEnd-incStart-3))
  Setmatch=oMatches(0) '确定只有一组捕捉时,要得到这一组匹配的子串,可以这样做,省去用ForEachmatchInoMatches……Next
  code=code&include(Mid(strFilename,1,InStrRev(strFilename,"/"))&match.SubMatches(1)) 'Mid(filename,1,InStrRev(filename,"/"))是在被引用的子文件名有路径时,把路径提取出来,加在子文件中传统引用的文件名前面,以找到正确的打开文件路径,因为动态引用时的文件路径是相对主文件而言的。要第二个匹配子串用SubMatches(1)
  incStart=InStr(incEnd,strBlock,"<!--#include")+13
 Loop
 str=Mid(strBlock,incEnd)
 str=Replace(str,"""","""""") '把单个双引号换成两个双引号
 str=Replace(str,VbCr,"")
 str=Replace(str,VbLf,"")
 str=Replace(str,VbCrLf,"")
 code=code&VbCrLf&"Response.Write"""&str&""""
 includeconvert=code
EndFunction
Functioninclude(filename)
 Dimre,content,fso,f,aspStart,aspEnd,code
 Setfso=CreateObject("scripting.FileSystemObject")
 Setf=fso.OpenTextFile(Server.MapPath(filename))
 content=f.ReadAll
 f.close
 Setf=nothing
 Setfso=nothing

 code=""
 aspEnd=1
 aspStart=InStr(aspEnd,content,"<%")+2
 Setre=newRegExp
 DoWhileaspStart>aspEnd+1
  '传统引用<!--#inclde肯定是在ASP代码段以外的,所以先转。
  code=code&includeconvert(re,filename,Mid(content,aspEnd,aspStart-aspEnd-2)