Mega Code Archive

 
Categories / C# / File Stream
 

Gets the relative path

using System; using System.Collections.Specialized; using System.Xml; using System.Text; using System.Text.RegularExpressions; namespace RSBuild {   /// <summary>   /// Utility methods.   /// </summary>   public static class Util   {         /// <summary>         /// Gets the relative path.         /// </summary>         /// <param name="source">The source.</param>         /// <param name="target">The target.</param>         /// <returns></returns>     public static string GetRelativePath(string source, string target)     {       string pathSource = Util.FormatPath(source);       string pathTarget = Util.FormatPath(target);       string[] sourceSegments = null;       string[] targetSegments = null;       int sourceToCommonRoot = 0, targetToCommonRoot = 0;       if (pathSource != "/")       {         sourceSegments = pathSource.Split('/');         sourceToCommonRoot = sourceSegments.GetUpperBound(0);       }       if (pathTarget != "/")       {         targetSegments = pathTarget.Split('/');         targetToCommonRoot = targetSegments.GetUpperBound(0);       }       StringBuilder relativePath = new StringBuilder();       int parentSegments = sourceToCommonRoot;       int i = 1;       while(sourceToCommonRoot >= i && targetToCommonRoot >= i)       {         if (string.Compare(sourceSegments[i], targetSegments[i], true) == 0)         {           parentSegments--;           i++;         }         else         {           break;         }       }       for(int k=0; k<parentSegments; k++)       {         relativePath.Append("../");       }       for(int m=i; m<=targetToCommonRoot; m++)       {         relativePath.AppendFormat("{0}/", targetSegments[m]);       }       return relativePath.ToString();     }   } }