using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace StyleCopContrib.Runner
{
///
/// A path utility class.
///
public static class PathUtility
{
#region Methods
///
/// Gets the relative path from a source to a target path.
///
/// The from source path.
/// The to target path.
/// The relative path.
public static string GetRelativePath(string fromPath, string toPath)
{
if (!Path.IsPathRooted(fromPath) || !Path.IsPathRooted(toPath))
{
throw new InvalidOperationException("Only fully qualified path are supported");
}
string relativePath;
string[] fromPathParts = fromPath.Split(Path.DirectorySeparatorChar);
string[] toPathParts = toPath.Split(Path.DirectorySeparatorChar);
int partIndex = 0;
while (partIndex < fromPathParts.Length)
{
if (fromPathParts[partIndex].ToUpperInvariant() != toPathParts[partIndex].ToUpperInvariant()) break;
partIndex++;
}
if (partIndex == 0)
{
relativePath = toPath;
}
else
{
string backPath = string.Join(Path.DirectorySeparatorChar.ToString(),
Enumerable.Repeat("..", fromPathParts.Length - partIndex).ToArray());
string forewardPath = string.Join(Path.DirectorySeparatorChar.ToString(), toPathParts, partIndex,
toPathParts.Length - partIndex);
if (!string.IsNullOrEmpty(backPath))
{
relativePath = string.Concat(backPath, Path.DirectorySeparatorChar, forewardPath);
}
else
{
relativePath = forewardPath;
}
}
return relativePath;
}
#endregion
}
}