24 | 03 | 2017

Checkif filename has illegal characters

The function below checks if a filename is valid or if a filename has illegal characters. This is a usefull check before saving a file.

 Function IsFilenameValid(ByVal name As String) As Boolean

        Dim i As Integer
        Dim dn, fn As String

        i = InStrRev(name, "\") : dn = Mid(name, 1, i) : fn = Mid(name, i + 1)
        
        If name Is Nothing Or Trim(fn) = "" Then
            Return False
        Else
            For Each badchar As Char In Path.GetInvalidFileNameChars
                If InStr(fn, badchar) > 0 Then
                    Return False
                End If
            Next
        End If

        If dn <> "" Then
            If InStr(dn, "\\") > 0 Then
                Return False
            End If
            For Each badChar As Char In Path.GetInvalidPathChars
                If InStr(dn, badChar) > 0 Then
                    Return False
                End If
            Next
            If Not System.IO.Directory.Exists(dn) Then
                Try
                    Directory.CreateDirectory(dn)
                    'Directory.Delete(dn)
                Catch
                    Return False
                End Try
            End If
        End If
        Return True
    End Function
Login

Sign up now and upload your code to the website.

Help us to continue.....
Statistics
Articles View Hits
2206758
Latest Articles