有效的文件名检查.什么是最好的方法? [英] Valid filename check. What is the best way?

查看:38
本文介绍了有效的文件名检查.什么是最好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅问题定位主题.

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

1) I recall seeing a really cool option in VB.NET using LINQ to match using "LIKE%'

2) 我知道正则表达式会起作用,我怀疑这会产生最短的代码,而且对于这样一个简单的测试来说可能不会太难阅读.

2) I know regular expressions will work and I suspect that will result in the shortest code and probably won't be too hard to read for such a simple test.

这就是我所做的.警告:你会讨厌它.

Here's what I did. Warning: You're gonna hate it.

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

推荐答案

现在很旧,但我看到了这个,只好添加一个新答案.当前接受的答案和其他答案比需要的要复杂得多.其实可以简化为一行:

Old now, but I saw this and just had to add a new answer. The current accepted and other answers are way more complicated than needed. In fact, it can be reduced to a single line:

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

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

Though I wouldn't recommend writing it that way. Break it up just a little bit to improve readability:

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

另外一点,通常处理文件系统问题的最佳方法是让文件系统告诉您:尝试打开或创建有问题的文件,并处理异常.这特别有效,因为无论如何您都可能不得不这样做.您在此处执行的任何其他验证都是重复的工作,您仍然需要将其放入异常处理程序中.

One other point here, is often the best way to deal with file system issues is to let the file system tell you: try to open or create the file in question, and deal with the exception. This works especially well, because you'll likely have to do this anyway. Any other validation you do here is duplicated effort for work you'll still have to put into an exception handler.

这篇关于有效的文件名检查.什么是最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆