Two simple file tricks [Path.InvalidPathChars]
Two simple file tricks
"1. How do I know if a file path string has valid characters without resorting to catching an exception?
bool IsFileNameValid(string fileName)
{
if(filename != null && fileName.IndexOfAny(Path.InvalidPathChars) != -1)
{ return false; }
else { return true; }
}
..."
Nice. Learn something new every day. Don't think I've seen Path.InvalidPathChars before. So much to learn.
sigh
2 comments:
Nice. VB.Net didn't like path despite the fact that one of their examples uses it. You need to put the namespace in front of it. VB also didn't like null or empty so I used len() instead but I haven't tested that. Here's the VB version for those of you who want it:
' Returns false if the string has any invalid filename characters in it, true otherwise.
Public Function IsFileNameValid(ByVal in_strFileName As String) As Boolean
Try
If (Len(in_strFileName) > 0 And in_strFileName.IndexOfAny(System.IO.Path.InvalidPathChars) > 1) Then
Return False
Else
Return True
End If
Catch ex As Exception
Call ShowErrorWithLog(ex.Message, ex.StackTrace, g_strFiles.strErrorLogFullFileName)
Return False
End Try
End Function
' Returns false if the string has any invalid filename characters in it, true otherwise.
Public Function IsValidFolderName(ByVal folderName As String) As Boolean
Try
If (Len(folderName) = 0 Or folderName.Trim().Length = 0) Then Return False
If (folderName.IndexOfAny(System.IO.Path.InvalidPathChars) <> -1) Then Return False
If (folderName.IndexOf(System.IO.Path.AltDirectorySeparatorChar) <> -1) Then Return False
If (folderName.IndexOf(System.IO.Path.DirectorySeparatorChar) <> -1) Then Return False
If (folderName.IndexOf(System.IO.Path.PathSeparator) <> -1) Then Return False
If (folderName.IndexOf(System.IO.Path.VolumeSeparatorChar) <> -1) Then Return False
If (folderName.StartsWith(".")) Then Return False
Return True
Catch ex As Exception
Call ShowErrorWithLog(ex.Message, ex.StackTrace, g_strFiles.strErrorLogFullFileName)
Return False
End Try
End Function
Nice.... Thank you
Post a Comment