Wednesday, November 3, 2010

Tip: How to get Relative Path in .NET

In .NET, there is no straight method available to find a relative path either in Path class or other classes. Here is the utility method that will help to get you the relative path

       /// <summary>
       /// Get relative path for a given file path
       /// </summary>
       /// <param name="baseDirectory">Base directory</param>
       /// <param name="filePath">A file path</param>
       /// <returns>A relative path location</returns>
       public static string GetRelativePath(string baseDirectory, string filePath)
       {
          if (String.IsNullOrEmpty(baseDirectory))
              throw new ArgumentNullException("BaseDirectory");
          if (String.IsNullOrEmpty(filePath))
              throw new ArgumentNullException("FilePath");

          if (!baseDirectory.EndsWith("\\"))
              baseDirectory += "\\";

          System.Uri uri1 = new Uri(filePath);
          System.Uri uri2 = new Uri(baseDirectory);

          Uri relativeUri = uri2.MakeRelativeUri(uri1);

          return relativeUri.ToString();
       }

No comments:

Post a Comment