There is a user-entered string that should look like the full path to the file, picking up its program works with the specified in the file, as if to make the input validation occur before (! FileExist), because if the file must be created on the specified line, the program will crash with an unhandled exception. developments:

string pattern = @"([a-zA-Z]://)((/w+//)+|(/w+./w+))" 

But I have suspicions that this construction will work incorrectly. Know, please tell me

  • ([a-zA-Z]: \ /) ((\ w + \ /) * (\ w +. \ w +)) that’s what happened - Garrus_En
  • "so that the check .. occurred before (! FileExist), because if the file is to be created on the specified line, the program will crash with an unhandled exception . " It is better to fix this than to try to check a regular way, which still may not exist. - Kromster
  • And an exception to catch who hinders? It can fly out anyway, if, say, you cannot write to the selected place or the folder itself does not exist where you need to write the file even if the path is correct. So it is better not to suffer with checking through regexps, but to catch and handle exceptions. - Zefick

1 answer 1

According to MSDN , instead of System.IO.File.Exists it is better to use System.IO.Path.GetInvalidPathChars , which returns a char[] array of invalid characters.

It is also better to check for null , and for a supported name format (such as the presence : inside the file / folder name)

those. verify the input is as follows:

  private bool isFileNameValid(string fileName) { if ((fileName == null) || (fileName.IndexOfAny(Path.GetInvalidPathChars()) != -1)) return false; try { var tempFileInfo = new FileInfo(fileName); return true; } catch (NotSupportedException) { return false; } } 
  • one
    Put a minus: i4.imageban.ru/out/2017/02/21/… - Andrew NOP
  • myPath.IndexOfAny(Path.GetInvalidPathChars()) == -1 , exactly, the colon : in the middle in this case ( myPath.IndexOfAny(Path.GetInvalidPathChars()) == -1 ) will be considered a valid file name. Changed the answer. - Nikolay.OAMP
  • And it would be good to check the string length - Nikolay.OAMP