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();
}
66240cookie-checkC# Get valid filename