GravatarBen Ramey's Blog
Scripture, programming problems, solutions and stories.

File Name Sanitizer One-Liner

I find myself often having to sanitize file names and paths because I’m creating files from some kind of user input that I’m unsure about. I found this handy way of doing this in one line today:

fileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (name, c) => name.Replace(c, ‘_’));

Note that the same goes for paths. The only thing that changes is the static method you use from Path:

filePath = Path.GetInvalidPathChars().Aggregate(filePath , (name, c) => name.Replace(c, ‘_’));

Comments