I have here a string(an input from the user) for a file path. I checked the string so that it will qualify the criteria:
- check for invalid characters for a file path
- will not accept absolute path (\Sample\text.txt)
Invalid characters are:
< > : ” / \ | ? *
I have tried catching these invalid characters in catch clause. It work except for ‘\’. It will accept ‘C:\\Sample\text.txt’ which is an invalid file path.
The following examples should be invalid paths:
- :\text.txt
- :text.txt
- \:text.txt
- \text.txt
- C:\\\text.txt
The ff. is an example of a valid path:
- C:\text.txt
I have been through similar questions posted here but none of them seemed to solve my issue.
What would be the best way to do such check?
You may use Path.GetFullPath, it will throw an exception if the path is invalid. You can have method like:
Sample code to test:
Output: