첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

▶ UrlCreateFromPath API 함수를 사용해 디렉토리/파일 경로에서 URI 구하기 예제

using System;

string path = @"d:\foo\..\foo";

Uri uri = GetURI(path);

Console.WriteLine(uri.AbsolutePath);
Console.WriteLine(uri.AbsoluteUri );

 

728x90

 

▶ UrlCreateFromPath API 함수를 사용해 디렉토리/파일 경로에서 URI 구하기

using System;
using System.Runtime.InteropServices;
using System.Text;

#region URI 구하기 - GetURI(path)

/// <summary>
/// URI 구하기
/// </summary>
/// <param name="path">경로</param>
/// <returns>URI</returns>
public Uri GetURI(string path)
{
    const string prefix      = @"\\";
    const string extended    = @"\\?\";
    const string extendedUNC = @"\\?\UNC\";
    const string device      = @"\\.\";

    const StringComparison comparison = StringComparison.Ordinal;

    if(path.StartsWith(extendedUNC, comparison))
    {
        path = $"{prefix}{path.Substring(extendedUNC.Length)}";
    }
    else if(path.StartsWith(extended, comparison))
    {
        path = $"{prefix}{path.Substring(extended.Length)}";
    }
    else if(path.StartsWith(device, comparison))
    {
        path = $"{prefix}{path.Substring(device.Length)}";
    }

    int length = 1;

    StringBuilder urlStringBuilder = new StringBuilder(length);

    int result = UrlCreateFromPath(path, urlStringBuilder, ref length, 0);

    if(length == 1)
    {
        Marshal.ThrowExceptionForHR(result);
    }

    urlStringBuilder.EnsureCapacity(length);

    result = UrlCreateFromPath(path, urlStringBuilder, ref length, 0);

    if(result == 1)
    {
        throw new ArgumentException("Argument is not a valid path.", "path");
    }

    Marshal.ThrowExceptionForHR(result);

    return new Uri(urlStringBuilder.ToString());
}

#endregion
#region 경로에서 URL 생성하기 - UrlCreateFromPath(path, urlStringBuilder, urlLength, reserved)

/// <summary>
/// 경로에서 URL 생성하기
/// </summary>
/// <param name="path">경로</param>
/// <param name="urlStringBuilder">URL 문자열 빌더</param>
/// <param name="urlLength">URL 길이</param>
/// <param name="reserved">예약</param>
/// <returns>처리 결과</returns>
[DllImport("shlwapi", CharSet=CharSet.Auto, SetLastError=true)]
private static extern int UrlCreateFromPath(string path, StringBuilder urlStringBuilder, ref int urlLength, int reserved);

#endregion
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요