Tuesday, August 01, 2006

Getting the relative path to a file, given its absolute path and a source folder (C#)

Here is some code that will get the relative path to a file, given its absolute path and the source folder from which the relative path should be computed. Code is in C# private static string GetRelativePath(string mainDirPath, string absoluteFilePath) { mainDirPath = mainDirPath.Substring(0,mainDirPath.LastIndexOf(Path.DirectorySeparatorChar)); string[] firstPathParts=mainDirPath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); string[] secondPathParts=absoluteFilePath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); int sameCounter=0; for(int i=0; isameCounter ) { newPath+=Path.DirectorySeparatorChar; } newPath+=".."; } if( newPath.Length==0 ) { newPath="."; } for(int i=sameCounter; i { newPath+=Path.DirectorySeparatorChar; newPath+=secondPathParts[i]; } return newPath; }

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.