The thing is you would expect something like this to be in the framework itself.
/// <summary>
/// Removes invalid characters from the string that is passed in.
/// </summary>
/// <param name="name">The name of the file.</param>
/// <returns>The safe name with invalid chars removed.</returns>
public static string GetSafeFileName(string name)
{
var safeName = new StringBuilder();
foreach (var c in name)
{
if ((from p in Path.GetInvalidFileNameChars() where p == c select p).Count() == 0)
{
safeName.Append(c);
}
}
return safeName.ToString();
}
Chris Martin posted an even tighter version of this code in the comments below. Thanks Chris.
Read more: merill.net