Remove Special characters in file name using Regular Expression in ASP.Net

rakibxl
 
on Sep 17, 2020 03:04 AM
3375 Views

Hello

I would like to Remove Special characters in a filename before uploading the file or I would like to give a message that filename is not correct.

What i am trying below way it is form Handler.ashx 

                    FileName = FileName.Trim.Replace(" ", "")
                    'Check if filename is valid
                    Dim regex As Regex = New Regex("[a-z][A-Z][.-_#[]?$%&(){}@][0-9]", RegexOptions.IgnoreCase)
                    Dim match As Match = regex.Match(Path.GetFileNameWithoutExtension(FileName)

                    If Not match.Success Then
                        context.Response.ContentType = "application/json"
                        context.Response.Write((New JavaScriptSerializer()).Serialize(New With {
                                    .success = False,
                                    .message = String.Format("{0} {1}",
                                                            FileName,
                                                            "File name is not valid please check and try again")}))
                        Exit Sub
                    End If

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
Mudassar
 
on Sep 17, 2020 07:15 AM
on Sep 17, 2020 07:22 AM

This way

C#

Regex.Replace(FileName, "[^a-zA-Z0-9.]+", "", RegexOptions.Compiled);

VB

Regex.Replace(FileName, "[^a-zA-Z0-9.]+", "", RegexOptions.Compiled)