Reputation: 787
Say I have the following string:
C:\folder1\folder2\ <- this is valid
C:\foler1\folder2 <- this is invalid
C:\folder1\folder2\folder3 <- invalid
Basically I want to check that the directory the user enters is in the format
C:\somthing\somthing\
anything else is invalid
Best approach? regex? or string functions?
Current vb approach:
Private Sub txtboxLocRoot_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtboxLocRoot.Validating
If txtboxLocRoot.Text.Split("\").Length - 1 <> 3 Then
MsgBox("Local root must be in the format 'C:\dir1\[folder name]\'", vbExclamation, "Error")
Return
End If
Dim foldernamearray() As String = Split(txtboxLocRoot.Text, "\")
pfoldername = foldernamearray(2)
txtboxLocRoot.Text = "C:\dir1\" & pfoldername & "\"
End Sub
Upvotes: 0
Views: 118
Reputation: 20464
Maybe not elegant, but better error cheking:
UPDATED
Private Sub Test()
Dim [Directory] As String = "C:\dir1\dir2\"
If DirectoryValidator([Directory]) Then
' Continue...
Else
' Throw
End If
End Sub
''' <summary>
''' Validates a directory path.
''' </summary>
''' <param name="Directory">
''' Indicates the directory to validate.
''' </param>
''' <returns><c>true</c> if validated successfully, <c>false</c> otherwise.</returns>
''' <exception cref="Exception">
''' Too less directories.
''' or
''' Too much directories.
''' or
''' Bad syntax.
''' or
''' Missing '\' character.
''' </exception>
Private Function DirectoryValidator(ByVal [Directory] As String) As Boolean
Select Case [Directory].Contains("\")
Case True
If [Directory].StartsWith("C:\", StringComparison.OrdinalIgnoreCase) AndAlso [Directory].EndsWith("\") Then
Dim PartsLength As Integer = [Directory].Split({"\"}, StringSplitOptions.RemoveEmptyEntries).Length
Dim InvalidChars As Char() = IO.Path.GetInvalidPathChars
If PartsLength < 3 Then
Throw New Exception("Too less directories.")
Return False
ElseIf PartsLength > 3 Then
Throw New Exception("Too much directories.")
Return False
ElseIf (From c As Char In [Directory] Where InvalidChars.Contains(c)).Any Then
Throw New Exception("Invalid characters.")
Return False
End If
Else
Throw New Exception("Bad syntax.")
Return False
End If
Case Else
Throw New Exception("Missing '\' character.")
Return False
End Select
Return True
End Function
Upvotes: 1
Reputation: 16003
To get up and running with some quick and dirty string functions why not something like:
If value.StartsWith("c:\") and value.EndsWith("\") then
'it's starting to look OK
'do some further testing for a single "\" in the middle section
End If
Then also use Path.GetInvalidFileNameChars and Path.GetInvalidPathChars to check there's not rubbish in there.
Upvotes: 1