Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
HowToDoThis committed Aug 11, 2021
1 parent 9022ac3 commit 9d0941a
Showing 1 changed file with 14 additions and 38 deletions.
52 changes: 14 additions & 38 deletions src/ICSharpCode.SharpZipLib/Core/PathUtils.cs
@@ -1,4 +1,5 @@
using System.IO;
using System.Linq;

namespace ICSharpCode.SharpZipLib.Core
{
Expand All @@ -12,46 +13,21 @@ public static class PathUtils
/// </summary>
/// <param name="path">A <see cref="string"/> containing path information.</param>
/// <returns>The path with the root removed if it was present; path otherwise.</returns>
/// <remarks>Unlike the <see cref="Path"/> class the path isn't otherwise checked for validity.</remarks>
public static string DropPathRoot(string path)
{
string result = path;

if (!string.IsNullOrEmpty(path))
{
if ((path[0] == '\\') || (path[0] == '/'))
{
// UNC name ?
if ((path.Length > 1) && ((path[1] == '\\') || (path[1] == '/')))
{
int index = 2;
int elements = 2;

// Scan for two separate elements \\machine\share\restofpath
while ((index <= path.Length) && (((path[index] != '\\') && (path[index] != '/')) || (--elements > 0)))
{
index++;
}

index++;

if (index < path.Length)
result = path[index..];
else
result = "";
}
}
else if ((path.Length > 1) && (path[1] == ':'))
{
int dropCount = 2;
if ((path.Length > 2) && ((path[2] == '\\') || (path[2] == '/')))
dropCount = 3;

result = result.Remove(0, dropCount);
}
}

return result;
var invalidChars = Path.GetInvalidPathChars();
// If the first character after the root is a ':', .NET < 4.6.2 throws
var cleanRootSep = path.Length >= 3 && path[1] == ':' && path[2] == ':';

// Replace any invalid path characters with '_' to prevent Path.GetPathRoot from throwing.
// Only pass the first 258 (should be 260, but that still throws for some reason) characters
// as .NET < 4.6.2 throws on longer paths
var cleanPath = new string(path.Take(258)
.Select((c, i) => invalidChars.Contains(c) || (i == 2 && cleanRootSep) ? '_' : c).ToArray());

var stripLength = Path.GetPathRoot(cleanPath).Length;
while (path.Length > stripLength && (path[stripLength] == '/' || path[stripLength] == '\\')) stripLength++;
return path.Substring(stripLength);
}

/// <summary>
Expand Down

0 comments on commit 9d0941a

Please sign in to comment.