| 得到网站路径信息的一个小函数 |
| 作者:蓝鲸 来源:5D多媒体 加入时间:2006-3-21 www.cnitrc.com |
|
最近有个通用系统,因为系统需要发布一些XML文件到网站的固定位置中,但是系统在网站的位置却是非固定的,所以就需要判断网站的网址。虽然可以在WEB.CONFIG文件中设置,但改来改去,还是有些麻烦。我们可以通过定义一个函数对网站的网址加以判断。
比如现在目录是:website/article/admin/send.aspx,那么可以得到如下信息:
目录深度:PathDepth(2)
网站根目录相对路径:HomeRelativeSite(../../)
网址:HomeSite(website/)
HomePhysicalPath:网站物理路径
PagePhysicalPath:当前页物理路径
先定义结构
/// <summary> /// 当前页面执行时的其它页面等信息 /// 路径、网址均以"/"关闭 /// </summary> public struct WebPageInfo { public int PathDepth; // 当前目录相对根目录的深度 public string HomeRelativeSite; // 根目录相对于本页的相对路径 public string HomeSite; // 网站网址 public string HomePhysicalPath; // 网站的物理路径 public string PagePhysicalPath; // 页面的物理路径 } 函数:
/// <summary> /// 得到当前页面时的路径信息结构 /// </summary> public static WebPageInfo GetCurrentPathInfo() { HttpContext context = HttpContext.Current; WebPageInfo pageInfo = new WebPageInfo(); pageInfo.HomePhysicalPath = context.Request.ServerVariables["APPL_PHYSICAL_PATH"]; pageInfo.PagePhysicalPath = context.Request.ServerVariables["PATH_TRANSLATED"]; string splitStr = "\\/"; char[] ch = splitStr.ToCharArray(); string[] path1 = pageInfo.HomePhysicalPath.Split(ch); string[] path2 = pageInfo.PagePhysicalPath.Split(ch); // 路径深度 pageInfo.PathDepth = path2.Length - path1.Length; // 网站根目录相对于本面的相对路径 pageInfo.HomeRelativeSite = ""; if (pageInfo.PathDepth > 0) { for (int i = 1; i <= pageInfo.PathDepth; i++) { pageInfo.HomeRelativeSite += "../"; } } // 得到网站网址 string tmpPath = pageInfo.PagePhysicalPath.Substring(pageInfo.HomePhysicalPath.Length); string tmpHttp = "http://" + context.Request.ServerVariables["HTTP_HOST"] + context.Request.ServerVariables["PATH_INFO"]; pageInfo.HomeSite = tmpHttp.Substring(0, tmpHttp.Length - tmpPath.Length); return pageInfo; } |
|
|