如何:在 Visual Basic 中验证文件名和路径

此示例返回一个 Boolean 值,该值指示字符串是表示文件名还是路径。 验证检查名称是否包含文件系统不允许的字符。

示例:

Function IsValidFileNameOrPath(ByVal name As String) As Boolean
    ' Determines if the name is Nothing.
    If name Is Nothing Then
        Return False
    End If

    ' Determines if there are bad characters in the name.
    For Each badChar As Char In System.IO.Path.GetInvalidPathChars
        If InStr(name, badChar) > 0 Then
            Return False
        End If
    Next

    ' The name passes basic validation.
    Return True
End Function

此示例不检查名称是否错误地放置冒号或没有名称的目录,或者名称长度是否超过系统定义的最大长度。 它还不会检查应用程序是否有权访问具有指定名称的文件系统资源。

另请参阅