运行类似的代码
StreamReader sr
=
new
StreamReader(
"
Test.txt
"
);
运行时会提示:"Could not find file 'C:"windows"system32"Test.txt".
这就是路径不对造成的
幸好在asp.net的request对象中有许多与路径相关的属性
ApplicationPath | 程序的虚拟根目录路径 |
CurrentExecutionFilePath | 当前请求的虚拟路径 |
FilePath | |
Path | |
PathInfo | |
PhysicalApplicationPath | 程序虚拟根目录的物理路径 |
PhysicalPath | 请求URL的物理路径 |
RawUrl | 当前请求的原始URL |
Url | 当前请求的URL信息 |
例如 如果我有一个名为ASPNETC的网站 它是我网站根目录下的一个子目录C:\Webs
输出如下:
ApplicationPath: "/"
CurrentExecutionFilePath: /aspnetc/testpath.aspx
FilePath: /aspnetc/testpath.aspx
Path: /aspnetc/testpath.aspx
PathInfo:
PhysicalApplicationPath: C:\webs\
PhysicalPath: C:\webs\aspnetc\testpath.aspx
RawUrl: /aspnetc/testpath.aspx
RawUrl包含QueryString信息 PathInfo可以用来Url重写
非常有用的 "~" and Page.ResolveUrl 两者结合起来能很方便的获取路径
"~"代表当前应用程序的根目录,经常在控件中使用,用来定位图片,css等文件的位置。
如果应用程序搬家了,放到不同的根目录下面,则会出现问题
Page的ResolveUrl正是用来解决这个问题
如果你的程序在"/SomeDir"
Page.ResolveUrl("~/images/image1.jpg") 返回 "/Somedir/images/image1.jpg"
在根目录
Page.ResolveUrl("~/images/image1.jpg") will simply return "/images/image1.jpg"
Server.MapPath方法相关
Server.MapPath("/") Server.MapPath("~")得到当前应用程序根目录的物理路径
Server.MapPath(".")得到当前目录的物理路径
Server.MapPath("..")得到父目录的物理路径
用Path.Combine连接路径
//
Returns C:"testdir"images"image1.jpg
Path.Combine( @" C: " testdir " , @ " Images " image1.jpg " );
Path.Combine( @" C: " testdir " , @ " Images " image1.jpg " );
原文:http://dotnetslackers.com/articles/aspnet/ASPNetPathsExplained.aspx