using System.Collections.Generic;
public static readonly char[] ReservedCharacters = new[] { '"', '!', '*', '\'', '(', ')', ';', ':', '@', '&', '=', '+', '$', '/', '?', '%', ',', '#', '[', ']', ' ' };
public static void Main()
var fileNames = new Dictionary<string, string>
{"><myFile *%@|?.txt", "myFile.txt"},
{"myFile.png", "myFile.png"}
foreach (var fileName in fileNames)
var cleanedFileName = CleanFileName(fileName.Key);
if (string.Equals(cleanedFileName, fileName.Value))
Console.WriteLine("PASS - '{0}' => '{1}'.", fileName.Key, fileName.Value);
Console.WriteLine("FAILED - Expected '{0}' but received '{1}'.", fileName.Value, cleanedFileName);
public static string CleanFileName(string fileName)
if (string.IsNullOrEmpty(fileName)) return fileName;
fileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
return ReservedCharacters.Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));