指定されたキャストは、後期結合を使用してMaileItem.Addressentryからmapiobjectを取得する無効です
-
26-10-2019 - |
質問
Outlookを使用した後期バインディングを使用して、MaileItem.AddressentryのMapiobjectを取得しようとしています。
「例外が呼び出されたターゲットによってスローされている」を取得し続けており、「指定されたキャストの内的例外は無効」であり、理由はわかりません。 Google検索などでは何も出ていません。
まず、Mapiobjectは非推奨であり、Intellisenseを介して見えないが機能することを知っています。
遅いバインディングなしではオブジェクトを問題なく取得できます。
これがコードです:
/// <summary>
/// Gets the MAPI Object from the AddressEntry of the new recipient.
/// </summary>
/// <param name="senderName">The name of the sender to add to the recipients.</param>
/// <param name="outlookApplication">The Outlook Application instance.</param>
private static object GetMapiObject(string senderName, object outlookApplication)
{
var mailItem = InvokeMember("CreateItem", outlookApplication, new object[] { 0 });
var recipients = GetProperty("Recipients", mailItem);
var recipient = InvokeMember("Add", recipients, new object[] { senderName });
InvokeMember("Resolve", recipient, new object[] {});
var addressEntry = GetProperty("AddressEntry", recipient);
var mapiObject = GetProperty("MAPIOBJECT", addressEntry); // Error occurs here.
return mapiObject;
}
/// <summary>
/// Gets a property of an instance by its name
/// </summary>
/// <param name="propertyName">The property name to get.</param>
/// <param name="instance">The object to get the property from.</param>
/// <returns>The resulting object.</returns>
private static object GetProperty(string propertyName, object instance)
{
Type type = instance.GetType();
return type.InvokeMember(propertyName, BindingFlags.GetProperty, null, instance, new object[] { });
}
/// <summary>
/// Invoke an object by its method and type - takes parameters.
/// </summary>
/// <param name="method">The method to invoke.</param>
/// <param name="instance">The object that contains the method to invoke.</param>
/// <param name="parameters">The parameters to pass to the method.</param>
/// <returns>The resulting object.</returns>
private static object InvokeMember(string method, object instance, object[] parameters)
{
try
{
Type type = instance.GetType();
return type.InvokeMember(method, BindingFlags.InvokeMethod, null, instance, parameters);
}
catch (Exception ex)
{
switch (method)
{
case "SaveAsFile":
throw new System.IO.IOException("Error occurred during \"SaveAsFile\" for attachments. Attachment filename may be too long. ", ex);
default:
throw new TargetInvocationException("Handled error at Invoke Member. Method Name: " + method, ex);
}
}
}
解決
あなたがあなたのようにMapiインターフェイスを使用する必要がない限り、私は強く使用することを強くお勧めします Mapiex CodeProjectでプロジェクト。
これにより、MAPIの統合は非常にスムーズに行われました。
そして、最悪の場合、ソースコードは、このような特定の質問に光を当てることができます。
他のヒント
第一に、Mapiobjectは廃止されず、目に見えません。第二に、あなたのコードはどこで実行されますか? Outlook.exe以外のexeの場合(つまり、コードはcomアドインにない)、mapiinitialize()を呼び出す必要があります。
所属していません StackOverflow