Mega Code Archive

 
Categories / C# / File Stream
 

Creates a relative path to targetFile that is relative to path

using System; using System.IO; using System.Text; public class Util {     public static string CreateRelativePath(string targetFile, string path)     {         if ((File.GetAttributes(path) & FileAttributes.Directory) != FileAttributes.Directory)         {             path = Path.GetDirectoryName(path);         }         string[] absDirs = path.Split('\\');         string[] relDirs = targetFile.Split('\\');         int length = absDirs.Length < relDirs.Length ? absDirs.Length :         relDirs.Length;         int lastCommonRoot = -1;         int index;         for (index = 0; index < length; index++)         {             if (absDirs[index] == relDirs[index]) lastCommonRoot = index;             else break;         }         if (lastCommonRoot == -1)         {             return Path.GetFullPath(targetFile);         }         StringBuilder relativePath = new StringBuilder();         for (index = lastCommonRoot + 1; index < absDirs.Length; index++)         {             if (absDirs[index].Length > 0) relativePath.Append("..\\");         }         for (index = lastCommonRoot + 1; index < relDirs.Length - 1; index++)         {             relativePath.Append(relDirs[index] + "\\");         }         relativePath.Append(relDirs[relDirs.Length - 1]);         return relativePath.ToString();     } }