C# Get valid filename

Date: 2022-08-29

// Builds a string out of valid chars and an _ for invalid ones
public static string GetValidFileName(string filename)
{
var invalidFileNameChars = Path.GetInvalidFileNameChars();
var pattern = new Regex("_+");
var onlyValidChars = new string(filename.Select(ch => invalidFileNameChars.Contains(ch) ? '_' : ch).ToArray());
return pattern.Replace(onlyValidChars, "_").Trim('_').Trim();
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
66240cookie-checkC# Get valid filename
0 of 2000 max characters.