using System; using System.IO; namespace PKHeX.Core; /// /// Logic for sanitizing file names and paths. /// /// /// Converting raw data to file names, trusting the data can lead to filesystem issues with invalid characters. /// public static class PathUtil { /// /// Cleans the by removing any invalid filename characters. /// /// New string without any invalid characters. public static string CleanFileName(string fileName) { Span result = stackalloc char[fileName.Length]; int ctr = GetCleanFileName(fileName, result); if (ctr == fileName.Length) return fileName; return new string(result[..ctr]); } /// public static string CleanFileName(ReadOnlySpan fileName) { Span result = stackalloc char[fileName.Length]; int ctr = GetCleanFileName(fileName, result); if (ctr == fileName.Length) return fileName.ToString(); return new string(result[..ctr]); } /// /// Wish this were a ReadOnlySpan<char> instead of a char[]. /// private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars(); /// /// Removes any invalid filename characters from the input string. /// /// String to clean /// Buffer to write the cleaned string to /// Length of the cleaned string private static int GetCleanFileName(ReadOnlySpan input, Span output) { ReadOnlySpan invalid = InvalidFileNameChars; int ctr = 0; foreach (var c in input) { if (!invalid.Contains(c)) output[ctr++] = c; } return ctr; } }