convert a fully qualified path to relative path

convert a fully qualified path to relative path

Download torelativepath.zip

Synopsis:

torelativepath.cs


torelativepath.cs

Synopsis
using System;
using ut;

public class testtorelativepath
{
  public static string torelativepath(string path, string prefix)
  {
    string fqpath = path.ToLower().Replace('/', '\\');
    string root = prefix.ToLower().Replace('/', '\\');
    if (!fqpath.StartsWith(root)) 
      throw new Exception("path does not start with given prefix");

    if (root.Length == fqpath.Length) return "";
    return path.Substring(prefix.Length + (fqpath[root.Length] == '\\' ? 1 : 0));
  }

  //--- Tests
  public void test_emptycases()
  {
    utx.assert(torelativepath(@"", @""), "");
    utx.assert(torelativepath(@"c:\", @"c:\"), "");
  }
  public void test_normal()
  {
    utx.assert(torelativepath(@"c:\abc", @"c:\"), "abc");
    utx.assert(torelativepath(@"c:\abc\def", @"c:\abc"), "def");
    utx.assert(torelativepath(@"c:\abc\def", @"c:\"), @"abc\def");
    utx.assert(torelativepath(@"c:\abc\def", @"c:"), @"abc\def");
  }
  public void test_ignorecaseinprefix()
  {
    utx.assert(torelativepath(@"c:\abc", @"c:\"), "abc");
    utx.assert(torelativepath(@"c:\abc", @"C:\"), "abc");
    utx.assert(torelativepath(@"C:\abc", @"c:\"), "abc");
    utx.assert(torelativepath(@"C:\abc", @"C:\"), "abc");
    utx.assert(torelativepath(@"c:\aBc\def", @"c:\abC"), "def");
  }
  public void test_preservecaseinpath()
  {
    utx.assert(torelativepath(@"c:\Abc", @"c:\"), "Abc");
  }
  public void test_notaprefix()
  {
    try
    {
      utx.assert(torelativepath(@"c:\abc\def", @"c:\xyz"), "def");
      utx.assert("no excp thrown", false);
    } 
    catch(Exception )
    {
      utx.assert(true);
    }
  }
}






Contact me about content on this page using john_web-at-arrizza-dot-com
For Web Master or site problems contact: webadmin-at-arrizza-dot-com
Copyright John Arrizza (c) 2001-2010