| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="FileNameTextSanitizer.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Globalization; |
| | | 10 | | using System.IO; |
| | | 11 | | using System.Linq; |
| | | 12 | | using System.Text; |
| | | 13 | | |
| | | 14 | | namespace MyNet.Text.Sanitization; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Sanitizes text so it can be used as a file name. |
| | | 18 | | /// </summary> |
| | | 19 | | public sealed class FileNameTextSanitizer : ITextSanitizerTransform |
| | | 20 | | { |
| | 3 | 21 | | private static readonly HashSet<char> InvalidCharacters = [.. Path.GetInvalidFileNameChars()]; |
| | | 22 | | |
| | | 23 | | /// <inheritdoc/> |
| | | 24 | | public string Apply(string input, CultureInfo culture) |
| | | 25 | | { |
| | 12 | 26 | | ArgumentNullException.ThrowIfNull(input); |
| | 9 | 27 | | ArgumentNullException.ThrowIfNull(culture); |
| | | 28 | | |
| | 9 | 29 | | if (input.Length == 0) |
| | 0 | 30 | | return input; |
| | | 31 | | |
| | 9 | 32 | | var sb = new StringBuilder(input.Length); |
| | 234 | 33 | | foreach (var ch in input.Where(ch => !InvalidCharacters.Contains(ch))) |
| | | 34 | | { |
| | 108 | 35 | | sb.Append(ch); |
| | | 36 | | } |
| | | 37 | | |
| | 9 | 38 | | return sb.ToString().Trim(); |
| | | 39 | | } |
| | | 40 | | } |
| | | 41 | | |