@@ -71,19 +71,33 @@ public static void AddListEntry<TKey, TValue>(this IDictionary<TKey, List<TValue
7171 /// <summary>
7272 /// Obtains the relative path from the specified base path.
7373 /// </summary>
74- /// <param name="filespec ">The file path.</param>
75- /// <param name="folder ">The base path.</param>
74+ /// <param name="fileSpec ">The file path.</param>
75+ /// <param name="baseDirectory ">The base path.</param>
7676 /// <returns>The path of <paramref name="filespec" /> relative to <paramref name="folder" />.</returns>
77- public static string GetRelativePath ( string filespec , string folder ) {
78- //http://stackoverflow.com/a/703292/462805
77+ public static string GetRelativePath ( string fileSpec , string baseDirectory ) {
78+ if ( fileSpec is null ) throw new ArgumentNullException ( nameof ( fileSpec ) ) ;
79+ if ( baseDirectory is null ) throw new ArgumentNullException ( nameof ( fileSpec ) ) ;
7980
80- var pathUri = new Uri ( filespec ) ;
81- // Folders must end in a slash
82- if ( ! folder . EndsWith ( Path . DirectorySeparatorChar . ToString ( ) ) ) {
83- folder += Path . DirectorySeparatorChar ;
81+ return GetRelativePath ( new FileInfo ( fileSpec ) , new DirectoryInfo ( baseDirectory ) ) ;
82+ }
83+
84+ public static string GetRelativePath ( FileInfo fileSpec , DirectoryInfo baseDirectory ) {
85+ if ( fileSpec is null ) throw new ArgumentNullException ( nameof ( fileSpec ) ) ;
86+ if ( baseDirectory is null ) throw new ArgumentNullException ( nameof ( fileSpec ) ) ;
87+
88+ if ( baseDirectory . FullName . EndsWith ( Path . DirectorySeparatorChar . ToString ( ) ) ) {
89+ baseDirectory = new DirectoryInfo ( baseDirectory . FullName . TrimEnd ( Path . DirectorySeparatorChar ) ) ;
8490 }
85- var folderUri = new Uri ( folder ) ;
86- return Uri . UnescapeDataString ( folderUri . MakeRelativeUri ( pathUri ) . ToString ( ) . Replace ( '/' , Path . DirectorySeparatorChar ) ) ;
91+
92+ var relativePath = fileSpec . Name ;
93+ var currentDirectory = fileSpec . Directory ;
94+ while ( ! ( currentDirectory is null ) && ! string . Equals ( currentDirectory . FullName , baseDirectory . FullName , StringComparison . OrdinalIgnoreCase ) ) {
95+ relativePath = currentDirectory . Name + Path . DirectorySeparatorChar + relativePath ;
96+ currentDirectory = currentDirectory . Parent ;
97+ }
98+
99+ if ( currentDirectory is null ) return null ; //file is not inside the base directory
100+ return relativePath ;
87101 }
88102
89103 /// <summary>
0 commit comments