Windows file name - How do I check if a file name is valid?

I need a function, perhaps among Path Functions , that will check if the filename is correct. Really, I mean that the characters present in the line are valid (eg ?

, >

etc.). Unfortunately, there is no function. Browsing the net and I found several techniques, none of which I liked or found solid.

  • Using a regular expression to check the contents of the filename.
  • Generating a filename, possibly in a %TEMP%

    system path. If creation fails, the filename is (possibly) invalid. Otherwise, it is valid (and therefore deletes the file).
  • Write a function that checks for invalid characters in the filename (for example ?:*>

    )

Extended form of the function will check all invalid names (eg AUX

, CON

etc.), but this is not a problem (at least not yet).

Is there any documented / undocumented feature I might have missed to reliably check if the filename is ( not ).

+3


source to share


1 answer


Edit: The feature is PathCleanupSpec

now deprecated and no longer supported. See the section Requirements

at the end of the linked page for details .

Thanks Connor for the feature. For other readers, the name of the function PathCleanupSpec

. With which I did the following:



bool IsLegalFileName(LPCWSTR filename)
{
    WCHAR valid_invalid[MAX_PATH];
    wcscpy_s(valid_invalid, filename);

    int result = PathCleanupSpec(nullptr, valid_invalid);

    // If return value is non-zero, or if 'valid_invalid' 
    // is modified, file-name is assumed invalid
    return result == 0 && wcsicmp(valid_invalid, filename)==0;
}

      

+2


source







All Articles