Often times, I want to create folder or file names from some string but file and directory names need to be valid so I've created the following helper class to help me.
public static class FilePathNameHelper { public static string GetValidPathName(string pathName, char goodCharReplacement) { return ReplaceBadWithGood(pathName, Path.GetInvalidPathChars(), goodCharReplacement); } public static string GetValidFileName(string fileName, char goodCharReplacement) { return ReplaceBadWithGood(fileName, Path.GetInvalidFileNameChars(), goodCharReplacement); } private static string ReplaceBadWithGood(string subject, char[] badBoys, char good) { if (!string.IsNullOrWhiteSpace(subject) && subject.ToCharArray().Intersect(badBoys).Any()) { subject = badBoys.Aggregate(subject, (current, bad) => current.Replace(bad, good)); } return subject; } }
It's quite easy to use:
var goodFileName = FilePathNameHelper.GetValidFileName("some bad file name<>.txt",'-');
goodFileName should contain "some bad file name--.txt".