Files
benramey.com-gatsby.js/src/posts/2011/08/24/file-name-sanitizer-one-liner.md
2020-09-24 19:50:41 -05:00

703 B
Raw Blame History

layout, title, date, description, categories, tags
layout title date description categories tags
post File Name Sanitizer One-Liner 2011-08-24 File Name Sanitizer One-Liner
programming
command-line

I find myself often having to sanitize file names and paths because Im creating files from some kind of user input that Im 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, _));