tags:

views:

901

answers:

4

See subject of positing for question.

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

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
A: 

Frankly, I'd just use the FileInfo object built in to .NET, and check for an exception for invalidity. See this reference for details.

McWafflestix
The code might be trying to validate a path that it doesn't have access to though.
patjbs
Exactly. As in my case.
Velika
Using exceptions to handle control flow is bad practice!
Bob King
@BobKing: tell it to microsoft; it'd be great to have a validate() method on their FileInfo, but they've chosen to go with the exception route.
McWafflestix
+1  A: 

It is a regex and C# but:

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 );
}
Dana Holt
Is this OS independent? I'd be cautious just if the app ever gets run under Mono.
Bob King
+2  A: 

How about Path.GetInvalidFileNameChars and Path.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
Bob King
A surprise answer! Well done!
Velika
how can this possibly work? Because if the filename already has invalid characters in it, then attempting to get the Filename (line 1) is going to exception, because GetFilename calls CheckInvalidPathChars and therefore throws the exception
Paul Farry
A: 

Even though this is quite old, it's still valid, and I ended up here looking for the solution to how to check the filename for invalid characters. I looked at the accepted answer and found a few holes.

Hopefully these modifications are of some use to someone else.

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
Paul Farry