很經(jīng)常使用到的一個功能,但在在網(wǎng)上卻一直沒有找到相關(guān)的解決方法,今天借著項目應(yīng)用到的機會寫了兩個將絕對路徑轉(zhuǎn)換為虛擬路徑封裝好的方法
將web站點下的絕對路徑轉(zhuǎn)換為相對于指定頁面的虛擬路徑
/**//// <summary>
/// 將web站點下的絕對路徑轉(zhuǎn)換為相對于指定頁面的虛擬路徑
/// </summary>
/// <param name="page">當(dāng)前頁面指針,一般為this</param>
/// <param name="specifiedpath">絕對路徑</param>
/// <returns>虛擬路徑, 型如: ../../</returns>
public static string convertspecifiedpathtorelativepathforpage(page page, string specifiedpath)
{
// 根目錄虛擬路徑
string virtualpath = page.request.applicationpath;
// 根目錄絕對路徑
string pathrooted = hostingenvironment.mappath(virtualpath);
// 頁面虛擬路徑
string pagevirtualpath = page.request.path;
if (!path.ispathrooted(specifiedpath) || specifiedpath.indexof(pathrooted) == -1)
{
throw new exception(string.format("/"{0}/"是虛擬路徑而不是絕對路徑!", specifiedpath));
}
// 轉(zhuǎn)換成相對路徑
//(測試發(fā)現(xiàn),pathrooted 在 vs2005 自帶的服務(wù)器跟在iis下根目錄或者虛擬目錄運行似乎不一樣,
// 有此地方后面會加"/", 有些則不會, 為保險起見判斷一下)
if (pathrooted.substring(pathrooted.length - 1, 1) == "http://")
{
specifiedpath = specifiedpath.replace(pathrooted, "/");
}
else
{
specifiedpath = specifiedpath.replace(pathrooted, "");
}
string relativepath = specifiedpath.replace("http://", "/");
string[] pagenodes = pagevirtualpath.split('/');
// 減去最后一個頁面和前面一個 "" 值
int pagenodescount = pagenodes.length - 2;
for (int i = 0; i < pagenodescount; i++)
{
relativepath = "/.." + relativepath;
}
if (pagenodescount > 0)
{
// 如果存在 ".." , 則把最前面的 "/" 去掉
relativepath = relativepath.substring(1, relativepath.length - 1);
}
return relativepath;
}
第二個方法顯然是從第一個方法中的前部分抽取出來的,所以懶得去添加相關(guān)注釋 :p
將web站點下的絕對路徑轉(zhuǎn)換為虛擬路徑
/**//// <summary>
/// 將web站點下的絕對路徑轉(zhuǎn)換為虛擬路徑
/// 注:非web站點下的則不轉(zhuǎn)換
/// </summary>
/// <param name="page">當(dāng)前頁面指針,一般為this</param>
/// <param name="specifiedpath">絕對路徑</param>
/// <returns>虛擬路徑, 型如: ~/</returns>
public static string convertspecifiedpathtorelativepath(page page, string specifiedpath)
{
string virtualpath = page.request.applicationpath;
string pathrooted = hostingenvironment.mappath(virtualpath);
if (!path.ispathrooted(specifiedpath) || specifiedpath.indexof(pathrooted) == -1)
{
return specifiedpath;
}
if (pathrooted.substring(pathrooted.length - 1, 1) == "http://")
{
specifiedpath = specifiedpath.replace(pathrooted, "~/");
}
else
{
specifiedpath = specifiedpath.replace(pathrooted, "~");
}
string relativepath = specifiedpath.replace("http://", "/");
return relativepath;
}
將虛擬路徑轉(zhuǎn)絕對路就沒什么好說的了, httprequest.mappath 方法專門干這事
新聞熱點
疑難解答
圖片精選