sanitizeFilename method
Sanitizes this string for use as a filename: removes invalid characters and optional length cap.
Removes or replaces characters that are typically invalid in filenames:
\ / : * ? " < > | and control characters. Replaces with replacement (default _).
If maxLength is greater than 0, truncates to that length (after sanitization).
Example:
'file:name?.txt'.sanitizeFilename(); // 'file_name_.txt'
'a/b/c'.sanitizeFilename(replacement: '-'); // 'a-b-c'
'long name'.sanitizeFilename(maxLength: 4); // 'long'
Implementation
@useResult
String sanitizeFilename({
String replacement = '_',
int maxLength = 0,
}) {
if (isEmpty) return this;
// Common invalid filename chars on Windows and Unix
final String sanitized = replaceAll(RegExp(r'[\s\\/:*?"<>|\x00-\x1f]'), replacement)
.replaceAll(RegExp(r'\.{2,}'), replacement) // no ..
.replaceAll(RegExp(r'^\.+'), replacement); // no leading .
final String one = RegExp.escape(replacement);
final String trimmed = sanitized.replaceAll(RegExp('$one+'), replacement).trim();
if (trimmed.isEmpty) return '';
if (maxLength > 0 && trimmed.length > maxLength) {
return trimmed.replaceRange(maxLength, trimmed.length, '');
}
return trimmed;
}