Valid filename check. What is the best way?
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 );
}
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
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.