可爱女生卡通图片:Server对象MapPath方法

来源:百度文库 编辑:偶看新闻 时间:2024/05/04 18:39:26

Server对象MapPath方法返回与Web服务器上的指定虚拟路径相对应的物理文件路径。
这在实际中也是很有用的,一般情况下,文件路径是用虚拟路径来表示,但有时必须使用物理路径,比如文件上传或对服务器上的文件进行操作,就必须使用物理路径。Server对象提供的MapPath方法,可以从一个有效虚拟路径下的任何文件上提取相应的实际物理路径。

MapPath方法的语法如下:
Server.MapPath(path)
path
:指定相对或虚拟路径或文件名,返回实际路径。

例如:
<%
    SerVer.MapPath("./Myfile.asp")
    Server.MapPalh("Myfile.asp")
%>

若在所给定的path参数前加“/”或“\”符号,则表示要把虚拟的全路径映射成完整的实际路径,即MapPath方法返回路径时将Path视为完整的虚拟路径。如果不是以斜杠开始,则MapPath方法返回与.asp文件中已有路径的相对路径。由于ASP要求在存取文件夹、文件或数据库数据时必须使用实际路径,所以在这种情况下,可以使用Server.MapPath(path)方法,将path指定的虚拟路径转换成实际路径。

Server.MapPath的用法
./当前目录
/根目录
../上层目录(相对当前来说)

如果当前的网站目录为D:\wwwroot    浏览的页面路径为D:\wwwroot\company\news\show.asp
在show.asp页面中使用
Server.MapPath("./")   返回路径为:D:\wwwroot\company\news
Server.MapPath("/")    返回路径为:D:\wwwroot
Server.MapPath("../")   返回路径为:D:\wwwroot\company
server.MapPath(request.ServerVariables("Path_Info")) 
Request.ServerVariables("Path_Translated")  
上面两种方式返回路径为 D:\wwwroot\company\news\show.asp

尽可能地使用Server.MapPath
尽可能地使用Server.MapPath()来表示存储在服务器上的文件,而不要用静态绝对路径。因为,如果采用静态绝对路径,当web路径发生变化时,将导致文件路径表达错误,从而不得不修改原静态路径。而使用Server.MapPath()表示的路径就不必再做修改。


比如,以下的代码就不是好的方法:
<%
whichfile="D:\inetpub\wwwroot\whatever\junk.txt"
Set fs = CreateObject("Scripting.FileSystemObject")
Set thisfile = fs.OpenTextFile(whichfile, 1, False)
tempSTR=thisfile.readall
response.write tempSTR
thisfile.Close
set thisfile=nothing
set fs=nothing
%>
建议使用下面的代码来完成同样的功能:
<%
whichfile=server.mappath("\whatever\junk.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
Set thisfile = fs.OpenTextFile(whichfile, 1, False)
tempSTR=thisfile.readall
response.write tempSTR
thisfile.Close
set thisfile=nothing
set fs=nothing
%>