Wednesday, June 10, 2015

VB.net - Sanitize file name to remove illegal characters such * : \ / < > | " ? [ ] ; = + & £ $

When you develop a system that allow user to upload file, you need to take care the file types, permission and it name. To avoid naming convention that are illegal, you need to sanitize file name and remove any illegal character and replace the character with something else such underscore ("_") which is acceptable. Below are the code you neeed.
private static string MakeValidFileName(string name)
{
  string invalidChars = Regex.Escape( new string( Path.GetInvalidFileNameChars() ) );
  string invalidReStr = string.Format( @"[{0}]+", invalidChars );
  return Regex.Replace( name, invalidReStr, "_" );
}
This function are very helpful for filtering file name using regular expression (regex) and GetInvalidFileNameChars() function. For file path, you can change it with GetInvalidPathChars() function to sanitize file path from your input.

No comments:

Post a Comment