Search code examples
windowswinapifilesystemsshellexecute

Windows ShellExecuteW with filename that exceeds MAX_PATH (260 characters)


I am struggling to understand what may be causing the issue in my case.

I am using

ShellExecuteW('open', 'explorer.exe', '/select,[file_name]', None, win32con.SW_SHOW)

What I am trying to do is open the file in the OS, highlight it, and bring the File Explorer to the foreground. This works fine for most cases, but when I try to open a file that exceeds the MAX_PATH limit (260 characters), the file doesn't open, and instead it takes me to the "My Files" page.

I have tried prepending "\\?\" to the beginning of my file name, because that is what other Stack Overflow posts said to do with regards to overriding the MAX_PATH limit, but it has not changed the situation.

Does the ShellExecuteW function not allow for files that exceed MAX_PATH? And, if so, is there any workaround I could use?


Solution

  • I read some cases, about this issue. Find this article:Long Paths in .NET, Part 1 of 3 [Kim Hamilton]

    If you prefix the file name with "\?\" and call the Unicode versions of the Windows APIs, then you can use file names up to 32K characters in length. In other words, the \?\ prefix is a way to enable long paths while working with the Windows file APIs.

    and:

    Long paths with the \?\ prefix can be used in most of the file-related Windows APIs, but not all Windows APIs.

    I also test ShellExcuteW with \\?\,it failed. Working well with SHOpenFolderAndSelectItems

    CoInitialize(NULL);
    
        LPCWSTR file_name ;//Change the path according to your needs
    
        PIDLIST_ABSOLUTE pidl;
        if (SUCCEEDED(SHParseDisplayName(file_name, 0, &pidl, 0, 0)))
        {
            ITEMIDLIST idNull = { 0 };
            LPCITEMIDLIST pidlNull[1] = { &idNull };
            SHOpenFolderAndSelectItems(pidl, 1, pidlNull, 0);
            ILFree(pidl);
        }
    

    Note:CoInitialize or CoInitializeEx must be called before using SHOpenFolderAndSelectItems. Not doing so causes SHOpenFolderAndSelectItems to fail.