Check valid filename Win32 API

drjackool 956 Reputation points
2021-09-05T16:13:59.233+00:00

Hi
Is there a Win32 API to check filename validity (for illegal chars and names) or I have to implement it?

Thanks

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,630 questions
{count} votes

Accepted answer
  1. drjackool 956 Reputation points
    2021-09-06T08:07:18.263+00:00

    Finally I implement it:

    // This function replaces illegal chars in file name by _
    // pstrOut must point to a buffer with MAX_PATH size
    void MakeLegalFileName(LPCTSTR pstrIn, LPTSTR pstrOut)
    {
        ASSERT(pstrIn);
        ASSERT(pstrOut);
    
        LPCTSTR pIn = pstrIn;
        LPTSTR pOut = pstrOut;
        LPTSTR pRightTrimPos = pstrOut;
        int nLen = 0;
        *pstrOut = _T('\0');
    
        while (*pIn != _T('\0') && nLen++ < MAX_PATH)
        {
            if (*pIn > 31)
            {
                switch (*pIn)
                {
                case _T('<'):
                case _T('>'):
                case _T(':'):
                case _T('"'):
                case _T('/'):
                case _T('\\'):
                case _T('|'):
                case _T('?'):
                case _T('*'):
                    *pOut = _T('_');
                    pOut++;
                    break;
    
                default:
                    if (*pIn != _T(' ') || *pstrOut != _T('\0')) // trim left spaces
                    {
                        *pOut = *pIn;
                        if (*pOut != _T('.') && *pOut != _T(' ')) // trim right spaces & dots
                            pRightTrimPos = pOut + 1;
    
                        pOut++;
                    }
                    break;
                }
            }
            else
            {
                *pOut = _T('_');
                pOut++;
            }
            pIn++;
        }
    
        *pRightTrimPos = _T('\0');
    
    
        static const TCHAR* szSpecialNames[22] = {
             _T("CON"), _T("PRN"), _T("AUX"), _T("NUL"),
             _T("COM1"), _T("COM2"), _T("COM3"), _T("COM4"), _T("COM5"), _T("COM6"), _T("COM7"), _T("COM8"), _T("COM9"),
             _T("LPT1"), _T("LPT2"), _T("LPT3"), _T("LPT4"), _T("LPT5"), _T("LPT6"), _T("LPT7"), _T("LPT8"), _T("LPT9")
        };
    
        int nOutStrLen = pRightTrimPos - pstrOut;
        if (nOutStrLen == 3)
        {
            for (int i = 0; i < 4; i++)
            {
                if (_tcsicmp(pstrOut, szSpecialNames[i]) == 0)
                {
                    pstrOut[2] = _T('_');
                    return;
                }
            }
        }
        else if (nOutStrLen == 4)
        {
            for (int i = 4; i < 22; i++)
            {
                if (_tcsicmp(pstrOut, szSpecialNames[i]) == 0)
                {
                    pstrOut[3] = _T('_');
                    return;
                }
            }
        }
    }
    

2 additional answers

Sort by: Most helpful
  1. metablaster 91 Reputation points
    2021-09-05T17:06:05.417+00:00

    There is an API called PathCleanupSpec that will attempt to remove illegal characters,
    You don't have to use resultant path, because your goal is to determine if anything was removed
    which means you know the path was bad.

    You know the path was bad trough return value of PCS_REMOVEDCHAR which means "Removed one or more invalid characters."
    Other return values need to be handled as well to get correct result.

    https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-pathcleanupspec

    0 comments No comments

  2. Sam of Simple Samples 5,516 Reputation points
    2021-09-05T19:13:56.027+00:00

    Unless someone knows of or finds something better, you can use a regular expression. You do not specify a language; the vs-general tag is neither a language nor an API. There are some possible regexes in Regular Expression Library. In C# you can use the Path.GetInvalidPathChars Method in a regex, something like:

    Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");  
    
    0 comments No comments