CleanFileName

CSharp · Console

/Program.cs

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		 var fileNames = new Dictionary<string, string>
            {
                {">myFile.txt", "myFile.txt"},
                {"<myFile.txt", "myFile.txt"},
                {"my cool file?", "my cool file"},
                {"this |file|", "this file"},
                {"this *bad* file", "this bad file"},
                {"goodFile Name", "goodFile Name"}
            };

            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);
                else
                    Console.WriteLine("FAILED - Expected '{0}' but received '{1}'.", fileName.Value, cleanedFileName);
            }
		
	}
	
	public static string CleanFileName(string fileName)
	{
    	return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
	}
}
;