Monday, August 18, 2008

Using Linq extension methods with arrays

I was generating a file path and file name from user text.

This routine was vulnerable to chars illegal to the file system in the user text.

I needed to strip any illegal chars from the user text.  

The Path class has two static methods which return path and file name illegal chars.

These are:

Path.GetInvalidPathChars( ) -> char[]

Path.GetInvalidFileNameChars( ) -> char[]

In order to strip both I wanted to create the set union of these two arrays.

The Linq set extension methods return IEnumerable which cannot be easily copied to a new array.  

In the end I used the following to generate a set comprising the union of both sets of illegal chars.

List illegals = new List( Path.GetInvalidPathChars( ).Union( Path.GetInvalidFileNameChars( ) ) );

Note that if you wish to change the file extension it is important to add '.' to the list of illegal chars.  Failure to do so may result in your filename being truncated at the '.'.