Skip to content

Commit 9d0941a

Browse files
committed
1 parent 9022ac3 commit 9d0941a

File tree

1 file changed

+14
-38
lines changed

1 file changed

+14
-38
lines changed

src/ICSharpCode.SharpZipLib/Core/PathUtils.cs

+14-38
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.IO;
2+
using System.Linq;
23

34
namespace ICSharpCode.SharpZipLib.Core
45
{
@@ -12,46 +13,21 @@ public static class PathUtils
1213
/// </summary>
1314
/// <param name="path">A <see cref="string"/> containing path information.</param>
1415
/// <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>
1616
public static string DropPathRoot(string path)
1717
{
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);
5531
}
5632

5733
/// <summary>

0 commit comments

Comments
 (0)