2014-02-20 92 views
0

說我有以下字符串:含vb.net驗證字符串backslahes

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

有效作爲「是正確的格式字符串」的文件系統上存在不檢查實際的目錄 –

+0

你知道如何用字符串函數和/或正則表達式來完成它,只需要關於哪個選項的建議?或者你需要幫助開始使用字符串函數/正則表達式? – hawbsl

+0

無法讓正則表達式工作,我有vb解決方案,它使用拆分工作。 –

回答

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.GetInvalidFileNameCharsPath.GetInvalidPathChars檢查有沒有垃圾在那裏。

+0

不錯,看起來更優雅一點,我目前的做法 –

1

也許不是優雅,但更好的錯誤cheking:

修訂

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