Search code examples
c#pinvoke

SetupVerifyInfFile - The parameter is incorrect. How to use C# pinvoke


I have problem with calling/implementing SetupVerifyInfFile.
When I call the VerifyInfFile function, I receive Exception "The parameter is incorrect".

    [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool SetupVerifyInfFile(
        string FileName,
        IntPtr AltPlatformInfo,
        ref IntPtr InfSignerInfo);

    [StructLayout(LayoutKind.Sequential)]
    public struct SP_INF_SIGNER_INFO
    {
        public int CbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string CatalogFile;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DigitalSigner;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DigitalSignerVersion;
    }

    public static void VerifyInfFile(string infPath)
    {
        SP_INF_SIGNER_INFO infSignerInfo = default;
        infSignerInfo.CbSize = Marshal.SizeOf(infSignerInfo);
        var infSignerPtr = Marshal.AllocHGlobal(infSignerInfo.CbSize);

        try
        {
            Marshal.StructureToPtr(infSignerInfo, infSignerPtr, false);
            if (!SetupVerifyInfFile(infPath, IntPtr.Zero, ref infSignerPtr))
                throw new Exception("Error calling SetupVerifyInfFile().", new 
                                     Win32Exception(Marshal.GetLastWin32Error()));
        }
        finally
        {
            Marshal.FreeHGlobal(infSignerPtr);
        }
    }

Solution

  • There are four obvious mistakes that I can see:

    1. The third parameter you pass as ref IntPtr InfSignerInfo. It is a mistake to pass this as ref. As documented, this parameter is a pointer to the struct. So you need to remove the ref.
    2. You don't specify a character set for SP_INF_SIGNER_INFO and so will get the default character set which is ANSI. That doesn't match CharSet.Auto in your function declaration.
    3. You use the wrong value for CbSize. You provide the size of a pointer, but you need to provide the size of the structure, Marshal.SizeOf(typeof(SP_INF_SIGNER_INFO)).
    4. You have used an incorrect value for MAX_PATH. The correct value is 260, and not 256.