Validate a file name on Windows

后端 未结 11 1982
一生所求
一生所求 2020-11-29 23:28
public static boolean isValidName(String text)
{
    Pattern pattern = Pattern.compile(\"^[^/./\\\\:*?\\\"<>|]+$\");
    Matcher matcher = pattern.matcher(text         


        
11条回答
  •  一整个雨季
    2020-11-30 00:17

    You can check all the reserved names (AUX, CON, and the like) and then use this code:

    bool invalidName = GetFileAttributes(name) == INVALID_FILE_ATTRIBUTES && 
            GetLastError() == ERROR_INVALID_NAME;
    

    to check for any additional restriction. But note that if you check for a name in a non existant directory you will get ERROR_PATH_NOT_FOUND whether the name is really valid or not.

    Anyway, you should remember the old saying:

    It's easier to ask for forgiveness than it is to get permission.

提交回复
热议问题