Asc > ?

ADO DOT NET

Centurion
Joined
Dec 20, 2006
Messages
160
Hi,
I want to convert this function to VB.NET:
Visual Basic:
Private Function FilterFileName(ByVal FileName As String) As String
   FilterFileName = Empty
   Dim MyLoop As Integer
   For MyLoop = 1 To Len(FileName)
    If Asc(Mid$(FileName, MyLoop, 1)) >= 97 And Asc(Mid$(FileName, MyLoop, 1)) <= 122 Or _
       Asc(Mid$(FileName, MyLoop, 1)) >= 65 And Asc(Mid$(FileName, MyLoop, 1)) <= 90 Or _
       Asc(Mid$(FileName, MyLoop, 1)) >= 48 And Asc(Mid$(FileName, MyLoop, 1)) <= 57 Or _
       Asc(Mid$(FileName, MyLoop, 1)) = 32 Or _
       Asc(Mid$(FileName, MyLoop, 1)) = 45 Or _
       Asc(Mid$(FileName, MyLoop, 1)) = 95 Then
        FilterFileName = FilterFileName & Mid$(FileName, MyLoop, 1)
    End If
   Next
End Function
Everything is alright, I just cannot find the new Asc() method in .NET.
Each old method has a .NET version, for example InStr instead of Mid$ but where is new method for ASC()?
Thanks.
 
Instead of the Mid() function, you can use the String.Chars property to get an individual character. Its quicker and returns a Char value, which you can compare with > and < without using the Asc() method.
Visual Basic:
Private Function FilterFileName(ByVal FileName As String) As String
   FilterFileName = Empty
   Dim MyLoop As Integer
   For MyLoop = 1 To Len(FileName)
    If FileName.Chars(MyLoop) >= "a"c And FileName.Chars(MyLoop) <= "z"c Or _
       FileName.Chars(MyLoop) >= "A"c And FileName.Chars(MyLoop) <= "Z"c Or _
       FileName.Chars(MyLoop) >= "0"c And FileName.Chars(MyLoop) <= "9"c Or _
       FileName.Chars(MyLoop) = " "c Or _
       FileName.Chars(MyLoop) = "-"c Or _
       FileName.Chars(MyLoop) = "_"c Then
        FilterFileName &= FileName.Chars(MyLoop)
    End If
   Next
End Function
You could make it even simpler, too, by using the functions of the Char type.
[Vb]
Private Function FilterFileName(ByVal FileName As String) As String
FilterFileName = Empty
Dim MyLoop As Integer
For MyLoop = 1 To Len(FileName)
Dim C As Char = FileName.Chars(MyLoop)
If Char.IsLetterOrDigit(C) Or _
C = " "c Or _
C = "-"c Or _
C = "_"c Then
FilterFileName &= FileName.Chars(MyLoop)
End If
Next
End Function[/CODE]
The System.IO.Path class has some functions that might make things simpler for you, too.
 
You might also use RegEx

Visual Basic:
Imports System.Text.RegularExpressions;

Dim pattern as String = "^[a-zA-Z0-9_\s-]+$"
Dim expression as Regex = new Regex(pattern)

If expression.IsMatch(YourInputVariable) = True Then
    ' Valid file name
Else
    'Bad file name
End If

This will provide you with a more controlled file name than System.IO.Path methods will give you.
 
Back
Top