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
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))
Frankly, I'd just use the FileInfo object built in to .NET, and check for an exception for invalidity. See this reference for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With