code_junkie

In C# check that filename is *possibly* valid (not that it exists)

Nov 13th, 2011
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. bool bOk = false;
  2. try
  3. {
  4. new System.IO.FileInfo(fileName);
  5. bOk = true;
  6. }
  7. catch (ArgumentException)
  8. {
  9. }
  10. catch (System.IO.PathTooLongException)
  11. {
  12. }
  13. catch (NotSupportedException)
  14. {
  15. }
  16. if (!bOk)
  17. {
  18. ...
  19. }
  20. else
  21. {
  22. ...
  23. }
  24.  
  25. Directory.GetLogicalDrives() // Returns an array of strings like "c:"
  26. Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
  27. Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.
  28.  
  29. bool IsValidFilename(string testName)
  30. {
  31. string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
  32. Regex containsABadCharacter = new Regex(regexString);
  33.  
  34. if (containsABadCharacter.IsMatch(testName)
  35. {
  36. return false;
  37. }
  38.  
  39. // Check for drive
  40. string pathRoot = Path.GetPathRoot(testName);
  41. if (Directory.GetLogicalDrives().Contains(pathRoot))
  42. {
  43. // etc
  44. }
  45.  
  46. // other checks for UNC, drive-path format, etc
  47.  
  48. return true;
  49. }
  50.  
  51. char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters
  52.  
  53. Path.GetPathRoot(string); // will return the root.
  54.  
  55. System.IO.DriveInfo.GetDrives()
  56.  
  57. System.IO.Path.GetInvalidFileNameChars();
  58. System.IO.Path.GetInvalidPathChars();
Add Comment
Please, Sign In to add comment