Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid filename check. What is the best way?

Tags:

vb.net

See subject of positing for question.

1) I recall seeing a really cool option in VB.NET using LINQ to match using "LIKE%'

2) I know regular expressions will work and I suspect that will result in the shortest code and probably won't be too hard to read for such a simple test.

Here's what I did. Warning: You're gonna hate it.

Private Shared Function FileNameIsOk(ByVal fileName As String) As Boolean

    For Position As Integer = 0 To fileName.Length - 1

        Dim Character As String = fileName.Substring(Position, 1).ToUpper
        Dim AsciiCharacter As Integer = Asc(Character)

        Select Case True

            Case Character = "_" 'allow _
            Case Character = "." 'allow .
            Case AsciiCharacter >= Asc("A") And AsciiCharacter <= Asc("A") 'Allow alphas
            Case AsciiCharacter >= Asc("0") AndAlso AsciiCharacter <= Asc("9") 'allow digits

            Case Else 'otherwise, invalid character
                Return False

        End Select

    Next

    Return True

End Function
like image 987
Chad Avatar asked Jun 18 '09 17:06

Chad


2 Answers

I cannot take credit for this one (well two) liner. I found it whilst googling-cant remember where I found it.

    Dim newFileName As String = "*Not<A>Good:Name|For/\File?"
    newFileName = String.Join("-", fileName.Split(IO.Path.GetInvalidFileNameChars))
like image 156
Kon Avatar answered Nov 01 '22 04:11

Kon


Frankly, I'd just use the FileInfo object built in to .NET, and check for an exception for invalidity. See this reference for details.

like image 23
Paul Sonier Avatar answered Nov 01 '22 05:11

Paul Sonier