Remove invalid characters from uploaded file name

Hi,

Today I have a requirement in my web application to remove the invalid characters from uploaded file name.

For this, I have created small function which removes the invalid characters from file name.

see the below function which I have used for the above requirement.


     string invalid = new string(Path.GetInvalidFileNameChars());
     foreach (char c in invalid)
     {
          fileName = fileName.Replace(c.ToString(), "");
     }
}

you can also replace it with “underscore sign” or any other valid character by using below code


     string invalid = new string(Path.GetInvalidFileNameChars());
     foreach (char c in invalid)
     {
          fileName = fileName.Replace(c.ToString(), "_");
     }
}

If you want to remove invalid characters from path then use below code


     string invalid = new string(Path.GetInvalidPathChars());
     foreach (char c in invalid)
     {
          fileName = fileName.Replace(c.ToString(), "_");
     }
}

Hope this will help.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>