RelativePath

  • Thread starter Thread starter Rick Strahl [MVP]
  • Start date Start date
R

Rick Strahl [MVP]

Does anybody know if there's some sort of function available to create a
relative path from a full path? Basically the reverse of Path.GetFullPath()?

Basically I need to pass in a path and a base path (usually the current
directory) and try to get back something like:

..\somefile.txt
...\..\somefile.txt

Before I write my own, i figure I better check <g>..

+++ Rick ---

--

Rick Strahl
West Wind Technologies
http://www.west-wind.com/
http://www.west-wind.com/weblog/
http://www.west-wind.com/wwThreads/
 
Thanks Mattias,

I ended up writing my own routine, which won't require interop. It's not
tested through all the way, but it works for what I need at this point:

/// <summary>
/// Returns a relative path string from a full path.
/// </summary>
/// <param name="FullPath">The path to convert. Can be either a file or a
directory</param>
/// <param name="BasePath">The base path to truncate to and replace</param>
/// <returns>
/// Lower case string of the relative path. If path is a directory it's
returned without a backslash at the end.
///
/// Examples of returned values:
/// .\test.txt, ..\test.txt, ..\..\..\test.txt, ., ..
/// </returns>
public static string GetRelativePath(string FullPath, string BasePath )
{
// *** Start by normalizing paths
FullPath = FullPath.ToLower();
BasePath = BasePath.ToLower();

if ( BasePath.EndsWith("\\") )
BasePath = BasePath.Substring(0,BasePath.Length-1);
if ( FullPath.EndsWith("\\") )
FullPath = FullPath.Substring(0,FullPath.Length-1);

// *** First check for full path
if ( FullPath.IndexOf(BasePath) > -1)
return FullPath.Replace(BasePath,".");

// *** Now parse backwards
string BackDirs = "";
string PartialPath = BasePath;
int Index = PartialPath.LastIndexOf("\\");
while (Index > 0)
{
// *** Strip path step string to last backslash
PartialPath = PartialPath.Substring(0,Index );

// *** Add another step backwards to our pass replacement
BackDirs = BackDirs + "..\\" ;

// *** Check for a matching path
if ( FullPath.IndexOf(PartialPath) > -1 )
{
if ( FullPath == PartialPath )
// *** We're dealing with a full Directory match and need to
replace it all
return
FullPath.Replace(PartialPath,BackDirs.Substring(0,BackDirs.Length-1) );
else
// *** We're dealing with a file or a start path
return FullPath.Replace(PartialPath+ (FullPath == PartialPath ?
"" : "\\"),BackDirs);
}
Index = PartialPath.LastIndexOf("\\",PartialPath.Length-1);
}

return FullPath;
}

--

Rick Strahl
West Wind Technologies
http://www.west-wind.com/
http://www.west-wind.com/weblog/
http://www.west-wind.com/wwThreads/
 
Back
Top