Why does Code Analysis in VS2013 RC lead me into a box canyon?

I ran Code Analysis on a utility I'm maintaining, and it advised me to change this:

private static extern int ReadMenu1File(string Menu1Path);

...to this:

private static extern int ReadMenu1File(UnmanagedType.LPWStr Menu1Path);

...with this verbiage: "Specify marshaling for P/Invoke string arguments To reduce security risk, marshal parameter 'Menu1Path' as Unicode, by setting DllImport.CharSet to CharSet.Unicode, or by explicitly marshaling the parameter as UnmanagedType.LPWStr. If you need to marshal this string as ANSI or system-dependent, specify MarshalAs explicitly, and set BestFitMapping=false; for added security, also set ThrowOnUnmappableChar=true."

...but when I did, it says, "The type name 'LPWStr' does not exist in the type 'System.Runtime.InteropServices.UnmanagedType'" and "'System.Runtime.InteropServices.UnmanagedType.LPWStr' is a 'field' but is used like a 'type'"

Code completion is not helping (no suggestions after typing "UnmanagedType.") nor is there a context menu option to add a missing using.

Jon Skeet
people
quotationmark

I suspect you've misinterpreted the advice. I suspect it was actually suggesting:

private static extern int ReadMenu1File([MarshalAs(UnmanagedType.LPWStr)]
                                        string Menu1Path);

EDIT: This fits in with the advice:

or by explicitly marshaling the parameter as UnmanagedType.LPWStr

That's not the same as saying "Change the parameter type to UnmanagedType.LPWStr" - it's just telling you that's how you ought to marshal the parameter.

The other recommendations are to be set on the [DllImport] instead.

people

See more on this question at Stackoverflow