Url Resolver클래스는 아래와 같은 기능들을 가지고 있습니다.
상대경로를 절대경로로 변환
상위 경로로 이동
Base URL 구하기
상대경로를 절대경로로 변환하는 기능에 북마크, 쿼리는 고려하지 않았으며, 일반적인 경우에 모두 정상적으로 동작합니다.
참고자료:
URL Relative Syntax and Base URLs - http://www.tcpipguide.com/free/t_URLRelativeSyntaxandBaseURLs-3.htm
URL 상대경로의 처리 - http://ljh131.tistory.com/6
public class UrlResolver
{
public static string GetBaseUrl(string url)
{
string baseUrl = url.Substring(0, url.LastIndexOf('/') + 1);
return baseUrl;
}
// return false if base url is root reached
public static bool GoUpOnePath(string baseUrl, out string newBaseUrl)
{
// 루트인지 체크 ('/' 개수가 3개이하면 중단)
int searchIndex = 0;
int count = 0;
int currentIndex = 0;
while (true)
{
currentIndex = baseUrl.IndexOf('/', searchIndex);
if (currentIndex != -1)
count++;
else
break;
searchIndex = currentIndex + 1;
}
if (count <= 3)
{
newBaseUrl = baseUrl;
return false;
}
// go up one
int secondOfLastSlashIndex = baseUrl.LastIndexOf('/', baseUrl.Length - 2);
newBaseUrl = baseUrl.Substring(0, secondOfLastSlashIndex + 1);
return true;
}
/*
* based on http://www.tcpipguide.com/free/t_URLRelativeSyntaxandBaseURLs-3.htm
* this function NOT include bookmark, query and new scheme url
*/
public static string GetAbsoluteUrl(string baseUrl, string relativeUrl)
{
// baseurl의 마지막은 반드시 /임
Debug.Assert(baseUrl.LastIndexOf('/') == baseUrl.Length - 1);
string[] relativePaths = { "//", "/", "./", "../", ".." };
bool resolveRelativePath = false;
do
{
resolveRelativePath = false;
foreach (string relativePath in relativePaths)
{
if (relativeUrl.IndexOf(relativePath) == 0)
{
resolveRelativePath = true;
switch (relativePath)
{
case "//": // 호스트 네임 지정
baseUrl = "http://";
break;
case "/": // 루트 지정
while (GoUpOnePath(baseUrl, out baseUrl))
;
break;
case "./": // 현재 디렉토리. 무시
break;
case "../": // 한단계 아래 디렉토리로 감. (더 이상 갈 수 없을때는 진행하지 않음.)
GoUpOnePath(baseUrl, out baseUrl);
break;
case "..": // 한단계 아래 디렉토리로 감. (../와 같음)
GoUpOnePath(baseUrl, out baseUrl);
break;
}
// remove relative path from url
relativeUrl = relativeUrl.Substring(relativePath.Length);
// reset loop
break;
}
}
} while (resolveRelativePath);
return baseUrl + relativeUrl;
}
}
'Programming > .NET' 카테고리의 다른 글
| URL 상대 경로, 절대 경로 변환 클래스 (C#) (0) | 2008/03/13 |
|---|---|
| C#으로 익스플로러 툴바 및 BHO만들기 (13) | 2007/11/07 |
| C#에서 unmanaged 함수 호출하기. (0) | 2007/08/31 |
| .NET 2.0 C#의 Configuration Manager (0) | 2007/08/30 |
| C# on multicore processor (or multi processor) - 멀티 프로세싱을 위한 C# (0) | 2007/07/30 |


Toolbar.zip
