在Console/WinForm/Silverlight等程式中,拿到一個絕對網址(例如: http:// localhost /WebApp/Folder/defaut.aspx)跟一個相對網址(例如: ../img/beauty.jpg),想計算出http:// localhost /WebApp/img/beauty.jpg!

過去我最常用的方法是用LastIndexOf比對最後一個"/"以拆出目錄的URL再自行組裝;其實,.NET早就有更好的解決方案...

string url = "http:// localhost/WebApp/Folder/defaut.aspx";
string relPath = "../img/beauty.jpg";
 
//設法去掉最後一個"/"後方的default.aspx,取得目錄路徑
//http:// localhost/WebApp/Folder
string pathUrl;
//方法1: LastIndexOf法
pathUrl = url.Substring(0, url.LastIndexOf('/'));
//方法2: LINQ走火入魔後會用的方法
string[] p = url.Split('/');
pathUrl = string.Join("/", 
    p.Reverse().Skip(1).Reverse().ToArray());
//金剛合體, 搞出不稱頭的http:// localhost/WebApp/Folder/../img/beauty.jpg
string finalUrl =
    pathUrl + "/" + relPath;
 
//太精彩了,LINQ居然可以這樣用~~~ 可惜還是零分
//用現成的工具呀,笨蛋!!
finalUrl = (new Uri(new Uri(url), relPath)).AbsoluteUri;
//輕鬆取得http:// localhost/WebApp/img/beauty.jpg,呀比!!

PS: 文中的URLhttp:// 與localhost中故意多空一格是為了防止Blog程式將其判定為可點選連結。


Comments

# by 變奏焙西諾

linq真的是用的太精彩了~

# by wei

喔~這絕不是笨問題,真的~真是超好用太感謝了

Post a comment