Validating file names for writing to disk

Suppose you have a system where a user can upload a file and they can specify the name of the file, or where a file is automatically generated and the name is created based on certain properties.

For instance, suppose a file is created and it's name will include information about the date it was created.
If the file name were created as

var fileName = string.Format("File created on {0}.txt", DateTime.Today);

the file name would be something similar to "File created on 02/05/2014 00:00:00.txt"

The characters / and : will both prevent the file from being saved as they are disallowed in file names in NTFS.

The filename can be automatically scrubbed of illegal characters easily using the following lines which utilise Path.GetInvalidFileNameChars

var illegalFileName = @"File created on 02/05/2014 00:00:00.txt";

var illegalChars = System.IO.Path.GetInvalidFileNameChars();

var legalFileName = new String(illegalFileName.Select(c => illegalChars.Contains(c) ? '-' : c).ToArray());

The code compares each character in the illegal file name to the characters returned by Path.GetInvalidFileNameChars() and if a match is found it returns a hyphen, otherwise it returns the character.
This allows us to construct a new string where any illegal characters have been replaced and the file can be safely written to disk with it''s new safe name.

The array returned by Path.GetInvalidFileNameChars() is dependent on the OS it is running on, some characters are illegal in Windows but allowed in Unix based systems such as OSX or Linux. As such, removing illegal characters on a Linux system and writing to a disk formatted in NTFS is not guaranteed to succeed.