Skip to content

Commit 7c79e06

Browse files
CopilotTyrrrzCopilot
authored
Fix filename sanitization for NTFS filesystems on non-Windows systems (#1455)
Co-authored-by: Tyrrrz <1935960+Tyrrrz@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent a74ba4d commit 7c79e06

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

DiscordChatExporter.Core/Utils/Extensions/PathExtensions.cs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,40 @@
11
using System;
22
using System.IO;
3+
using System.Linq;
34
using System.Text;
45

56
namespace DiscordChatExporter.Core.Utils.Extensions;
67

78
public static class PathExtensions
89
{
10+
// Characters that are invalid on common filesystems.
11+
// This is a union of invalid characters from Windows (NTFS/FAT32), Linux (ext4/XFS), and macOS (HFS+/APFS).
12+
// We use this instead of Path.GetInvalidFileNameChars() because that only returns OS-specific characters,
13+
// not filesystem-specific characters. This means that it's possible to use, for example, an NTFS drive on
14+
// Linux, which would allow the OS to create filenames with '?' but result in errors when writing to the filesystem.
15+
// https://github.com/Tyrrrz/DiscordChatExporter/issues/1452
16+
private static readonly char[] InvalidFileNameChars =
17+
[
18+
'\0', // Null character - invalid on all filesystems
19+
'/', // Path separator on Unix
20+
'\\', // Path separator on Windows
21+
':', // Reserved on Windows (drive letters, NTFS streams)
22+
'*', // Wildcard on Windows
23+
'?', // Wildcard on Windows
24+
'"', // Reserved on Windows
25+
'<', // Redirection on Windows
26+
'>', // Redirection on Windows
27+
'|', // Pipe on Windows
28+
];
29+
930
extension(Path)
1031
{
1132
public static string EscapeFileName(string path)
1233
{
1334
var buffer = new StringBuilder(path.Length);
1435

1536
foreach (var c in path)
16-
buffer.Append(!Path.GetInvalidFileNameChars().Contains(c) ? c : '_');
37+
buffer.Append(!InvalidFileNameChars.Contains(c) ? c : '_');
1738

1839
// File names cannot end with a dot on Windows
1940
// https://github.com/Tyrrrz/DiscordChatExporter/issues/977

0 commit comments

Comments
 (0)