Regular expressions in C# for file name validation

后端 未结 4 2016
小鲜肉
小鲜肉 2020-12-29 06:17

What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have \\/:*?\"<>| characters).

4条回答
  •  醉酒成梦
    2020-12-29 06:49

    This isn't as simple as just checking whether the file name contains any of System.IO.Path.GetInvalidFileNameChars (as mentioned in a couple of other answers already).

    For example what if somebody enters a name that contains no invalid chars but is 300 characters long (i.e. greater than MAX_PATH) - this won't work with any of the .NET file APIs, and only has limited support in the rest of windows using the \?\ path syntax. You need context as to how long the rest of the path is to determine how long the file name can be. You can find more information about this type of thing here.

    Ultimately all your checks can reliably do is prove that a file name is not valid, or give you a reasonable estimate as to whether it is valid. It's virtually impossible to prove that the file name is valid without actually trying to use it. (And even then you have issues like what if it already exists? It may be a valid file name, but is it valid in your scenario to have a duplicate name?)

提交回复
热议问题