Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows filename - How to check if filename would be valid?

I wanted a function, possibly amongst Path Functions, that would check if file-name would be valid. By valid, I meant if character present in the string are all valid (having no ?, > etc, for example). But sadly, there is no function. Browsing through the net, and SO, I found few techniques, none of them I liked, or found solid.

  • Using a regular expression to check the contents of filename.
  • Creating a file name, possibly in %TEMP% path of the system. If creation fails, the filename is (possibly) invalid. Otherwise, it is valid (and therefore, delete the file).
  • Write up a function, that checks if invalid characters are present in the filename (e.g. ?:*>)

An extended form of function would be to check all invalid names (like AUX, CON etc), but that's not an issue (at least for now).

Is there any documented/undocumented function, that I might have missed, which would reliably check if filename (not pathname) is valid.

like image 374
Ajay Avatar asked Sep 30 '22 10:09

Ajay


1 Answers

Edit: the PathCleanupSpec function is now deprecated and no longer supported. Refer to the Requirements section at the end of the linked page for details.


Thanks Connor, for the function. For other readers, the function name is PathCleanupSpec. Using which I have implemented 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;
}
like image 180
Ajay Avatar answered Oct 16 '22 22:10

Ajay