0

I have a C# application that needs to recognize whether a given string is a valid Windows file path that ends in a file name with extension. Currently I have:

public static bool IsValidWindowsFilePathWithFileName(string filepath)
{
    string scriptFilePathPattern = @"^[A-Za-z]:(\\\w+(\s*\w+)*)*(\\\w+(\s*\w+)*\.[a-zA-Z]\w*)$";
    return Regex.IsMatch(filepath, scriptFilePathPattern);
}

This normally works fine. However, if I put in something that ends with a long string, such as

"C:\Windows\System32\ThisIsALongBadFileName"

it takes several minutes to process. Is there a better way to do this?

Sach
  • 10,091
  • 8
  • 47
  • 84
William
  • 508
  • 3
  • 10
  • 18
  • 1
    What's wrong with one of the solutions in https://stackoverflow.com/q/62771/62576 Also, WIndows filenames are not required to end with an extension. – Ken White Jul 10 '18 at 22:28
  • Provide examples of what is valid, and what would be invalid. Saying a path is wrong...doesn't provide enough information. – ΩmegaMan Jul 10 '18 at 22:31
  • 1
    Please stop trying to validate filenames with strings or regular expressions. [That doesn't work](https://stackoverflow.com/questions/1976007). The only way to validate a filename is to try to create it and see if it throws an exception at runtime. – Dour High Arch Jul 10 '18 at 22:35
  • Several *minutes*? What are you running this on? – vzwick Jul 10 '18 at 23:37
  • Why are you not using File.Exists(string path)? – Shar1er80 Jul 11 '18 at 02:53
  • I'm not using File.Exists because the computer that the path is stored on may not be the same computer where the path is used. – William Jul 11 '18 at 12:34

2 Answers2

1

Where possible remove * (zero or more) and replace with + 1 or more. Every * used, adds to the backtracking of the parser. If you know there is not zero condition, don't put it in...use the +.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
1

I decided to simply accept that any file path which doesn't end in a slash is valid, rather than trying to police legitimate filenames.

William
  • 508
  • 3
  • 10
  • 18