Skip to content

PInvoke.FindFirstFileExFromApp does not set last error code #1636

@aicd0

Description

@aicd0

Actual behavior

PInvoke.FindFirstFileExFromApp does not set last error code when return value is HANDLE.INVALID_HANDLE_VALUE. According to official document:

If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.

Expected behavior

Marshal.GetLastWin32Error() returns correct error code after PInvoke.FindFirstFileExFromApp().

Repro steps

  1. NativeMethods.txt content:
FindClose
FindFirstFileExFromApp
FindNextFile
INVALID_HANDLE_VALUE
  1. Any of your own code that should be shared?
        private static unsafe HANDLE FindFirstFileExFromApp(
            string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
            out WIN32_FIND_DATAW findData, FINDEX_SEARCH_OPS fSearchOp,
            uint dwAdditionalFlags)
        {
            fixed (char* lpFileNameLocal = lpFileName)
            {
                WIN32_FIND_DATAW findDataLocal;
                HANDLE handle = PInvoke.FindFirstFileExFromApp(lpFileNameLocal, fInfoLevelId, &findDataLocal, fSearchOp, default, dwAdditionalFlags);
                if (handle == HANDLE.INVALID_HANDLE_VALUE)
                {
                    int errorCode = Marshal.GetLastWin32Error(); // returns 0
                    Logger.I(TAG, $"Unable to access '{lpFileName}' ({errorCode})");
                }

                findData = findDataLocal;
                return handle;
            }
        }

Context

  • CsWin32 version: 0.3.264
  • Win32Metadata version (if explicitly set by project):
  • Target Framework: net8.0-windows10.0.22621.0
  • LangVersion (if explicitly set by project): [e.g. 9]

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions