说我有以下字符串:
C:\folder1\folder2\ <- this is valid
C:\foler1\folder2 <- this is invalid
C:\folder1\folder2\folder3 <- invalid
基本上我想检查用户输入的目录是否为
格式 C:\somthing\somthing\
其他任何内容无效
最佳方法?正则表达式?或字符串函数?
当前的vb方法:
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
答案 0 :(得分:1)
要启动并运行一些快速而脏的字符串函数,为什么不能这样:
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
然后还使用Path.GetInvalidFileNameChars和Path.GetInvalidPathChars检查那里没有垃圾。
答案 1 :(得分:1)
也许不优雅,但更好的错误检查:
的修订版强> 的
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