有效文件名检查。什么是最好的方法?

时间:2009-06-18 17:58:05

标签: vb.net

请参阅提出问题的主题。

1)我记得在VB.NET中看到一个非常酷的选项,使用LINQ匹配使用“LIKE%'

2)我知道正则表达式会起作用,我怀疑这会产生最短的代码,并且可能不会因为这么简单的测试而难以阅读。

这就是我的所作所为。警告:你会讨厌它。

Private Shared Function FileNameIsOk(ByVal fileName As String) As Boolean

    For Position As Integer = 0 To fileName.Length - 1

        Dim Character As String = fileName.Substring(Position, 1).ToUpper
        Dim AsciiCharacter As Integer = Asc(Character)

        Select Case True

            Case Character = "_" 'allow _
            Case Character = "." 'allow .
            Case AsciiCharacter >= Asc("A") And AsciiCharacter <= Asc("A") 'Allow alphas
            Case AsciiCharacter >= Asc("0") AndAlso AsciiCharacter <= Asc("9") 'allow digits

            Case Else 'otherwise, invalid character
                Return False

        End Select

    Next

    Return True

End Function

12 个答案:

答案 0 :(得分:13)

现在老了,但我看到了这个,只需要添加一个新答案。当前接受和其他答案比需要的更复杂。事实上,它可以简化为一行:

Public Shared Function FilenameIsOK(ByVal fileName as String) as Boolean
    Return Not (Path.GetFileName(fileName).Intersect(Path.GetInvalidFileNameChars()).Any() OrElse Path.GetDirectoryName(fileName).Intersect(Path.GetInvalidPathChars()).Any()) 
End Function

虽然我不建议那样写。稍微分解一下以提高可读性:

Public Shared Function FilenameIsOK(ByVal fileName as String) as Boolean
    Dim file As String = Path.GetFileName(fileName)
    Dim directory As String = Path.GetDirectoryName(fileName)

    Return Not (file.Intersect(Path.GetInvalidFileNameChars()).Any() _
                OrElse _ 
                directory.Intersect(Path.GetInvalidPathChars()).Any()) 
End Function

另一点是,处理文件系统问题的最佳方法通常是让文件系统告诉您:只是尝试打开或创建有问题的文件,并处理异常。这非常有效,因为你可能不得不这样做。你在这里做的任何事情都是重复的工作,你仍然需要把它放到一个异常处理程序中。

答案 1 :(得分:10)

Path.GetInvalidFileNameCharsPath.GetInvalidPathChars怎么样?

Public Shared Function FilenameIsOK(ByVal fileNameAndPath as String) as Boolean
    Dim fileName = Path.GetFileName(fileNameAndPath)
    Dim directory = Path.GetDirectoryName(fileNameAndPath)
    For each c in Path.GetInvalidFileNameChars()
        If fileName.Contains(c) Then
            Return False
        End If
    Next
    For each c in Path.GetInvalidPathChars()
        If directory.Contains(c) Then
            Return False
        End If
    Next
    Return True
End Function

答案 2 :(得分:2)

这是一个正则表达式和C#但是:

using System;
using System.Text.RegularExpressions;

/// <summary>
/// Gets whether the specified path is a valid absolute file path.
/// </summary>
/// <param name="path">Any path. OK if null or empty.</param>
static public bool IsValidPath( string path )
{
    Regex r = new Regex( @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$" );
    return r.IsMatch( path );
}

答案 3 :(得分:1)

即使这已经很老了,它仍然有效,我最终在这里寻找如何检查无效字符的文件名的解决方案。我看了接受的答案,发现了几个洞。

希望这些修改对其他人有用。

Public Function FilenameIsOK(ByVal fileNameAndPath As String) As Boolean
    Dim fileName As String = String.Empty
    Dim theDirectory As String = fileNameAndPath

    Dim p As Char = Path.DirectorySeparatorChar

    Dim splitPath() As String
    splitPath = fileNameAndPath.Split(p)
    If splitPath.Length > 1 Then
        fileName = splitPath(splitPath.Length - 1)
        theDirectory = String.Join(p, splitPath, 0, splitPath.Length - 1)
    End If

    For Each c As Char In Path.GetInvalidFileNameChars()
        If fileName.Contains(c) Then
            Return False
        End If
    Next

    For Each c As Char In Path.GetInvalidPathChars()
        If theDirectory.Contains(c) Then
            Return False
        End If
    Next
    Return True
End Function

答案 4 :(得分:1)

试试这个

Public Function IsValidFileName(ByVal fn As String) As Boolean
    Try
        Dim fi As New IO.FileInfo(fn)
    Catch ex As Exception
        Return False
    End Try
    Return True
End Function

答案 5 :(得分:1)

基于Joel Coehoorns写得很好的解决方案,我添加了一些额外的功能进行验证。

    ''' <summary>
    ''' Check if fileName is OK
    ''' </summary>
    ''' <param name="fileName">FileName</param>
    ''' <param name="allowPathDefinition">(optional) set true to allow path definitions. If set to false only filenames are allowed</param>
    ''' <param name="firstCharIndex">(optional) return the index of first invalid character</param>
    ''' <returns>true if filename is valid</returns>
    ''' <remarks>
    ''' based on Joel Coehoorn answer in 
    ''' http://stackoverflow.com/questions/1014242/valid-filename-check-what-is-the-best-way
    ''' </remarks>
    Public Shared Function FilenameIsOK(ByVal fileName As String, _
                                        Optional ByVal allowPathDefinition As Boolean = False, _
                                        Optional ByRef firstCharIndex As Integer = Nothing) As Boolean

        Dim file As String = String.Empty
        Dim directory As String = String.Empty

        If allowPathDefinition Then
            file = Path.GetFileName(fileName)
            directory = Path.GetDirectoryName(fileName)
        Else
            file = fileName
        End If

        If Not IsNothing(firstCharIndex) Then
            Dim f As IEnumerable(Of Char)
            f = file.Intersect(Path.GetInvalidFileNameChars())
            If f.Any Then
                firstCharIndex = Len(directory) + file.IndexOf(f.First)
                Return False
            End If

            f = directory.Intersect(Path.GetInvalidPathChars())
            If f.Any Then
                firstCharIndex = directory.IndexOf(f.First)
                Return False
            Else
                Return True
            End If
        Else
            Return Not (file.Intersect(Path.GetInvalidFileNameChars()).Any() _
                        OrElse _
                        directory.Intersect(Path.GetInvalidPathChars()).Any())
        End If

    End Function

答案 6 :(得分:1)

我不能相信这一个(两个)班轮。我发现它,但谷歌搜索不记得我在哪里发现它。

    Dim newFileName As String = "*Not<A>Good:Name|For/\File?"
    newFileName = String.Join("-", fileName.Split(IO.Path.GetInvalidFileNameChars))

答案 7 :(得分:0)

坦率地说,我只是使用.NET内置的FileInfo对象,并检查无效的异常。有关详细信息,请参阅this参考。

答案 8 :(得分:0)

确定。好主意。 但是,当您使用数千个文件时,手动迭代“无效”字符并不是最好的方法。

Public BadChars() As Char = IO.Path.GetInvalidFileNameChars

For m = 0 To thousands_of_files - 1
    '..
    if currFile.Name.ToCharArray.Intersect(BadChars).Count > 1 Then
         ' the Name is invalid - what u gonna do? =)
    end if
    '..
    '..
Next

答案 9 :(得分:0)

试试这个

函数IsValidFileNameOrPath(ByVal name As String)As Boolean

Dim i As Integer         Dim dn,fn As String

    i = InStrRev(name, "\") : dn = Mid(name, 1, i) : fn = Mid(name, i + 1)
    MsgBox("directory = " & dn & " : file = " & fn)

    If name Is Nothing Or Trim(fn) = "" Then
        MsgBox("null filename" & fn)
        Return False
    Else
        For Each badchar As Char In Path.GetInvalidFileNameChars
            If InStr(fn, badchar) > 0 Then
                MsgBox("invalid filename" & fn)
                Return False
            End If
        Next
    End If

    If dn <> "" Then
        If InStr(dn, "\\") > 0 Then
            MsgBox("duplicate \ =  " & dn)
            Return False
        End If
        For Each badChar As Char In Path.GetInvalidPathChars
            If InStr(dn, badChar) > 0 Then
                MsgBox("invalid directory=  " & dn)
                Return False
            End If
        Next
        If Not System.IO.Directory.Exists(dn) Then
            Try
                Directory.CreateDirectory(dn)
                'Directory.Delete(dn)
            Catch
                MsgBox("invalid path =  " & dn)
                Return False
            End Try
        End If
    End If
    Return True
End Function

答案 10 :(得分:0)

Public Function IsValidFileName(nFile As String) As Boolean
    Try
        Dim S As String = Path.GetFileName(nFile)
    Catch
        Return False
    End Try
    Return True
End Function

答案 11 :(得分:-1)

这是一种简单的方法,即使在文件夹中也是如此:

    Try
        My.Computer.FileSystem.WriteAllText("aux", "Hello World!", False)
    Catch ex As Exception
        'do nothing or inform the user
    End Try