Sanitizes filenames
Implements rules documented by Microsoft + file name length truncation to 255 bytes - common on many modern file systems. Runs on any .net8 target platform.
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
Restrictions of Windows, Linux and OsX are alle combined to an replacemant pattern, that will sanitize any filename to be compatible with any of the OS and common filesystem restrictions.
Pattern | OS that dont support pattern | OS that support pattern | Example |
---|---|---|---|
Reserverd keywords | Windows | Linux, OsX | CON, PRN, AUX, ... |
Reserved chars | Linux, Windows, OsX | '/', '\0' | |
Reserved chars windows | Windows | Linux, OsX | '\', '""', ... |
InvalidTrailingChars | Windows | Linux, OsX | ' ', ',' |
Max length Linux | Linux, | Windows, OsX | 255 bytes |
Max length | Linux, Windows, OsX | 255 chars | |
Unicode surrogates | OsX, Linux | Windows | U+D800 - U+DFFF |
NotAssigned to unicode | OsX | Linux, Windows | U+67803, ... |