#12004/12/7 10:11:11
最近最个通用系统,因系统在网站的位置不一定是固定的,而且需要发布一些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;
}
非常大鱼