1
1
using System . IO ;
2
+ using System . Linq ;
2
3
3
4
namespace ICSharpCode . SharpZipLib . Core
4
5
{
@@ -12,46 +13,21 @@ public static class PathUtils
12
13
/// </summary>
13
14
/// <param name="path">A <see cref="string"/> containing path information.</param>
14
15
/// <returns>The path with the root removed if it was present; path otherwise.</returns>
15
- /// <remarks>Unlike the <see cref="Path"/> class the path isn't otherwise checked for validity.</remarks>
16
16
public static string DropPathRoot ( string path )
17
17
{
18
- string result = path ;
19
-
20
- if ( ! string . IsNullOrEmpty ( path ) )
21
- {
22
- if ( ( path [ 0 ] == '\\ ' ) || ( path [ 0 ] == '/' ) )
23
- {
24
- // UNC name ?
25
- if ( ( path . Length > 1 ) && ( ( path [ 1 ] == '\\ ' ) || ( path [ 1 ] == '/' ) ) )
26
- {
27
- int index = 2 ;
28
- int elements = 2 ;
29
-
30
- // Scan for two separate elements \\machine\share\restofpath
31
- while ( ( index <= path . Length ) && ( ( ( path [ index ] != '\\ ' ) && ( path [ index ] != '/' ) ) || ( -- elements > 0 ) ) )
32
- {
33
- index ++ ;
34
- }
35
-
36
- index ++ ;
37
-
38
- if ( index < path . Length )
39
- result = path [ index ..] ;
40
- else
41
- result = "" ;
42
- }
43
- }
44
- else if ( ( path . Length > 1 ) && ( path [ 1 ] == ':' ) )
45
- {
46
- int dropCount = 2 ;
47
- if ( ( path . Length > 2 ) && ( ( path [ 2 ] == '\\ ' ) || ( path [ 2 ] == '/' ) ) )
48
- dropCount = 3 ;
49
-
50
- result = result . Remove ( 0 , dropCount ) ;
51
- }
52
- }
53
-
54
- return result ;
18
+ var invalidChars = Path . GetInvalidPathChars ( ) ;
19
+ // If the first character after the root is a ':', .NET < 4.6.2 throws
20
+ var cleanRootSep = path . Length >= 3 && path [ 1 ] == ':' && path [ 2 ] == ':' ;
21
+
22
+ // Replace any invalid path characters with '_' to prevent Path.GetPathRoot from throwing.
23
+ // Only pass the first 258 (should be 260, but that still throws for some reason) characters
24
+ // as .NET < 4.6.2 throws on longer paths
25
+ var cleanPath = new string ( path . Take ( 258 )
26
+ . Select ( ( c , i ) => invalidChars . Contains ( c ) || ( i == 2 && cleanRootSep ) ? '_' : c ) . ToArray ( ) ) ;
27
+
28
+ var stripLength = Path . GetPathRoot ( cleanPath ) . Length ;
29
+ while ( path . Length > stripLength && ( path [ stripLength ] == '/' || path [ stripLength ] == '\\ ' ) ) stripLength ++ ;
30
+ return path . Substring ( stripLength ) ;
55
31
}
56
32
57
33
/// <summary>
0 commit comments