Recently I was working with parsing a .Resx file which stored file locations as relative locations (i.e. ..\..\..\Images\Logo.jpg ) and found that path combine does not work with such. I have often wished Path.Combine(DirectoryInfo, string) was valid but because Path is static I could not extend it. I ended up writing a short utility below which handles more variations than Path.Combine.
/// <summary> /// A utility to resolve ..\ in the relative path /// </summary>/// <param name="directory">Directory Information on the base </param> /// <param name="relativePath">The dotted relative path</param> /// <returns></returns> public static string CombinePath(DirectoryInfo directory, string relativePath) { while (relativePath.StartsWith(@"..\")) { relativePath = relativePath.Substring(3); directory = directory.Parent; } if (relativePath.StartsWith(@"~")) { if (System.Web.HttpContext.Current == null) { //An intelligent guess of the intent relativePath = relativePath.Substring(1); } else { return System.Web.HttpContext.Current.Server.MapPath(relativePath); } } return Path.Combine(directory.FullName, relativePath); } public static string CombinePath(string directory, string relativePath) { return CombinePath(new DirectoryInfo(directory), relativPath); }
No comments:
Post a Comment