Since upgrading to Visual Studio 16.8.1, I am getting many errors from the code analysis in my (somewhat old) VB.NET project.
One error is on the following DLLImport
<DllImport("MAPI32.DLL")> _
Private Shared Function MAPISendMail ( ByVal sess As IntPtr, _
ByVal hwnd As IntPtr, _
ByVal message As MapiMessage, _
ByVal flg As Integer, _
ByVal rsv As Integer ) As Integer
End Function
The error is
Error CA2101
To reduce security risk, marshal field 'MapiMessage.subject' as Unicode, by setting StructLayout.CharSet on 'MapiMessage' to CharSet.Unicode, or by explicitly marshaling the field as UnmanagedType.LPWStr. If you need to marshal this string as ANSI or system-dependent, specify MarshalAs explicitly, use the BestFitMapping attribute to turn best-fit mapping off, and for added security, to turn ThrowOnUnmappableChar on.
The structure MAPI message is defined as
<StructLayout(LayoutKind.Sequential)> _
Public Class MapiMessage
Public reserved As Integer
Public subject As String
Public noteText As String
Public messageType As String
Public dateReceived As String
Public conversationID As String
Public flags As Integer
Public originator As IntPtr
Public recipCount As Integer
Public recips As IntPtr
Public fileCount As Integer
Public files As IntPtr
End Class
I have tried specifying CharSet.Ansi on both the function
<DllImport("MAPI32.DLL", CharSet := CharSet.Ansi)> _
Private Shared Function MAPISendMail ( ByVal sess As IntPtr, _
ByVal hwnd As IntPtr, _
ByVal message As MapiMessage, _
ByVal flg As Integer, _
ByVal rsv As Integer ) As Integer
End Function
and the structure
<StructLayout(LayoutKind.Sequential, CharSet := CharSet.Ansi)> _
Public Class MapiMessage
...
End Class
and also tried specifying MarshalAs(UnmanagedType.LPStr) on the field subject.
<MarshalAs(UnmanagedType.LPStr)> _
Public subject As String
I have also tried specifying BestFitMapping = false and ThrowOnUnmappableChar = true, as suggested in the error message.
<DllImport("MAPI32.DLL", CharSet := CharSet.Ansi, BestFitMapping := False, ThrowOnUnmappableChar := True)> _
Private Shared Function MAPISendMail ( ByVal sess As IntPtr, _
ByVal hwnd As IntPtr, _
ByVal message As MapiMessage, _
ByVal flg As Integer, _
ByVal rsv As Integer ) As Integer
End Function
I am still getting the same error.
I have not yet tried using MAPISendMailW (and I haven't found a sample), but even if that provides a solution, surely there must be a way to marshal as ANSI without an error message.
What exactly do I have to do to fix this error?