Skip to content

Codeuctivity/SanitizeFilename

Repository files navigation

SanitizeFilename

Sanitizes file and directory names in a manner that is compatible with Windows, Linux and OsX.

.NET build and test NuGet Donate

Implements rules documented by Microsoft + file name length truncation to 255 bytes - common on many modern file systems. Runs on any .net8 target platform.

Example

using Codeuctivity;

string unsafeString = "file*Name";
string safeFileName = unsafeString.SanitizeFilename();
Console.WriteLine($"Unsafe: {unsafeString}");
//Unsafe: file*Name
Console.WriteLine($"Sanitized: {safeFileName}");
//Sanitized: file_Name

string safeFileNameOptionalReplacementChar = unsafeString.SanitizeFilename(' ');
Console.WriteLine($"SafeFileNameOptionalReplacementChar: {safeFileNameOptionalReplacementChar}");
//SafeFileNameOptionalReplacementChar: file Name

Rules

Restrictions of Windows, Linux and OsX are alle combined to an replacement pattern, that will sanitize any filename to be compatible with any of the OS and common filesystem restrictions.

Pattern OS that don't support pattern OS that support pattern Example
Reserved keywords Windows Linux, OsX CON, PRN, AUX, ...
Reserved chars Linux, Windows, OsX '/', '\0'
Reserved chars windows Windows Linux, OsX '\', '""', ...
Invalid trailing chars Windows Linux, OsX ' ', ','
Max length Linux Linux, Windows, OsX 255 bytes
Max length Linux, Windows, OsX 255 chars
Unpaired Unicode surrogates OsX, Linux Windows U+D800 - U+DFFF
NotAssigned to Unicode OsX Linux, Windows U+67803, ...