您的位置:首页 > 编程语言 > ASP

ASP.NET中关于路径(Path)的相关知识

2010-05-06 16:37 471 查看
也许你曾遇到过这样的情况
运行类似的代码

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");

NET中Path类的几个方法

1. Path.combine(string, string)
根据给出的两个路径, 返回一个路径.
例如:

string CompletePath = System.IO.Path.Combine(@"c:\MyApp", @"Images\skyline.jpg");
将会返回一个全路径 c:\MyApp\Images\skyline.jpg
第一个参数中有无"\"结尾都可以.

2. Path.GetExtension(string)
返回给定文件路径的扩展名.例如:
string FileExtention = System.IO.Path.GetExtention(@"C:\MyApp\Images\skyline.jpg");
将会返回 "jpg"

3. Path.GetFileName(string)
给出文件名的全路径,返回文件名(包括扩展名).例如:
string fileName = System.IO.Path.GetFileName(@"c:\MyApp\Images\skyline.jpg");
将会返回"skyline.jpg"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: