■ UrlCreateFromPath API 함수를 사용해 디렉토리/파일 경로에서 URI를 구하는 방법을 보여준다.
▶ UrlCreateFromPath API 함수를 사용해 디렉토리/파일 경로에서 URI 구하기 예제 (C#)
1 2 3 4 5 6 7 8 9 10 |
using System; string path = @"d:\foo\..\foo"; Uri uri = GetURI(path); Console.WriteLine(uri.AbsolutePath); Console.WriteLine(uri.AbsoluteUri ); |
▶ UrlCreateFromPath API 함수를 사용해 디렉토리/파일 경로에서 URI 구하기 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
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 |