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:
  • name - filename that needs to be sanitized
  • replaceChar - char used to replace all invalid file name characters
Implementation is available both in C# and VB.Net languages. Use buttons below to switch language visibility.

Implementation

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

Comments

Post new comment

  • Lines and paragraphs are automatically recognized. The <br /> line break, <p> paragraph and </p> close paragraph tags are inserted automatically. If paragraphs are not recognized simply add a couple blank lines.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
1 + 1 =
This simple math problem is designed for BOT - you just have to enter '7'.