How to sanitize a file name using LINQ

From this article you can learn how to sanitize a file name using simple LINQ query. SanitizeFilename function takes two parameters: Implementation is available both in C# and VB.Net languages. Use buttons below to switch language visibility.


System.Linq namespace needs to be put in usings.

public static string SanitizeFileName(string name, char replaceChar)
  return Path.GetInvalidFileNameChars().Aggregate(name, (current, c) => current.Replace(c, replaceChar));
Public Shared Function SanitizeFileName(name As String, replaceChar As Char) As String
  Return Path.GetInvalidFileNameChars().Aggregate(name, Function(current, c) current.Replace(c, replaceChar))
End Function