2007-12-11

How to convert absolute path to relative path in C# .Net

public static string Absolute2RelativePath(string basePath, string absolutePath)
{
string[] baseDirectories = basePath.Split('\\');
string[] absoluteDirectories = absolutePath.Split('\\');

// Get the shortest of the two paths
int length = baseDirectories.Length <>

// Use to determine where in the loop we exited
int lastCommonRoot = -1;
int index;

// Find common root
for (index = 0; index <>
{
if (baseDirectories[index] == absoluteDirectories[index])
{
lastCommonRoot = index;
}
else
{
break;
}
}

// If we didn't find a common prefix then throw
if (lastCommonRoot == -1)
{
return absolutePath;
}

// Build up the relative path
StringBuilder relativePath = new StringBuilder();

// Add on the ..
for (index = lastCommonRoot + 1; index <>
{
if (baseDirectories[index].Length > 0)
{
relativePath.Append("..\\");
}
}

// Add on the folders
for (index = lastCommonRoot + 1; index <>
{
relativePath.Append(absoluteDirectories[index] + "\\");
}
relativePath.Append(absoluteDirectories[absoluteDirectories.Length - 1]);

return relativePath;
}

This code was found on an another Blogger page, bit re-aligned and posted here.

No comments: