Skip to content

Commit

Permalink
Merge pull request #859 from DineshSolanki/#858-fix-invalid-character…
Browse files Browse the repository at this point in the history
…-in-filename

Fix #858 - Replaces invalid filename characters
  • Loading branch information
adamhathcock authored Jul 30, 2024
2 parents baf66db + 2d10df8 commit 06a983e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SharpCompress/Common/ExtractionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public static void WriteEntryToDirectory(
options ??= new ExtractionOptions() { Overwrite = true };

var file = Path.GetFileName(entry.Key.NotNull("Entry Key is null")).NotNull("File is null");
file = Utility.ReplaceInvalidFileNameChars(file);
if (options.ExtractFullPath)
{
var folder = Path.GetDirectoryName(entry.Key.NotNull("Entry Key is null"))
Expand Down
14 changes: 14 additions & 0 deletions src/SharpCompress/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SharpCompress.Readers;

namespace SharpCompress;
Expand Down Expand Up @@ -434,4 +435,17 @@ public static void SetBigUInt32(ref byte[] buffer, uint number, long offset)
buffer[offset + 2] = (byte)(number >> 8);
buffer[offset + 3] = (byte)number;
}

public static string ReplaceInvalidFileNameChars(string fileName)
{
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
var sb = new StringBuilder(fileName.Length);
foreach (var c in fileName)
{
var newChar = invalidChars.Contains(c) ? '_' : c;
sb.Append(newChar);
}

return sb.ToString();
}
}

0 comments on commit 06a983e

Please sign in to comment.