Skip to content

Commit

Permalink
fix(zip): avoid throwing on empty file name (#828)
Browse files Browse the repository at this point in the history
Co-authored-by: Dmitrii Makarov <dmakarov@spotware.com>
  • Loading branch information
piksel and dmakarov-spotware committed Mar 12, 2023
1 parent c19f0a4 commit 0ef7941
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/ICSharpCode.SharpZipLib/Core/PathUtils.cs
Expand Up @@ -16,6 +16,9 @@ public static class PathUtils
/// <returns>The path with the root removed if it was present; path otherwise.</returns>
public static string DropPathRoot(string path)
{
// No need to drop anything
if (path == string.Empty) return path;

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] == ':';
Expand All @@ -26,7 +29,7 @@ public static string DropPathRoot(string path)
var cleanPath = new string(path.Take(258)
.Select( (c, i) => invalidChars.Contains(c) || (i == 2 && cleanRootSep) ? '_' : c).ToArray());

var stripLength = Path.GetPathRoot(cleanPath).Length;
var stripLength = Path.GetPathRoot(cleanPath)?.Length ?? 0;
while (path.Length > stripLength && (path[stripLength] == '/' || path[stripLength] == '\\')) stripLength++;
return path.Substring(stripLength);
}
Expand Down
22 changes: 22 additions & 0 deletions test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs
Expand Up @@ -1815,5 +1815,27 @@ public void TestDescriptorUpdateOnAdd(UseZip64 useZip64)
}
}
}

/// <summary>
/// Check that Zip files can be created with an empty file name
/// </summary>
[Test]
[Category("Zip")]
public void HandlesEmptyFileName()
{
using var ms = new MemoryStream();
using (var zos = new ZipOutputStream(ms){IsStreamOwner = false})
{
zos.PutNextEntry(new ZipEntry(String.Empty));
Utils.WriteDummyData(zos, 64);
}
ms.Seek(0, SeekOrigin.Begin);
using (var zis = new ZipInputStream(ms){IsStreamOwner = false})
{
var entry = zis.GetNextEntry();
Assert.That(entry.Name, Is.Empty);
Assert.That(zis.ReadBytes(64).Length, Is.EqualTo(64));
}
}
}
}

0 comments on commit 0ef7941

Please sign in to comment.