2

突然得到一个 System.invalidcastexception: unable to cast COM object of type 'system._object' to interface type 'Microsoft.office.interop.outlook.mailitem' ... 到我写的一个运行良好的程序,现在 BAM!例外。

不知道为什么...请注意我是新手程序员。

这是我使用 Outlook 的代码片段:

using Microsoft.Office.Interop.Outlook;

static Microsoft.Office.Interop.Outlook.Application app = null;
static _NameSpace ns = null;
static MailItem item = null;
static MAPIFolder inboxFolder = null;
static MAPIFolder dest = null;
static void SendMail(string mailSubject, string htmlMailBody, string mailTo)
{
    Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
    NameSpace outlookNS = outlookApp.GetNamespace("MAPI");
    outlookNS.Logon(Missing.Value, Missing.Value, true, true);
    MailItem oMsg = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
    oMsg.To = mailTo;
    oMsg.Recipients.ResolveAll();
    StreamReader sr = new StreamReader(@"C:\Users\" + WindowsIdentity.GetCurrent().Name.Split('\\')[1] + @"\AppData\Roaming\Microsoft\Signatures\Default.htm");
    string signature = sr.ReadToEnd();
    oMsg.Subject = mailSubject;
    oMsg.HTMLBody = htmlMailBody + "<br><br>" + signature + "</font>";
    oMsg.Save();
    ((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send();
    oMsg = null;
    outlookNS = null;
    outlookApp = null;
}

app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

#region match - convert - extract
foreach (string tifFile in Directory.GetFiles(workFolder, "*.tif", SearchOption.TopDirectoryOnly))
{
    string currentFile = Path.GetFileNameWithoutExtension(tifFile);

    for (int i = 1; i <= inboxFolder.Items.Count; i++)
    {
        //##############CODE CRASHES HERE##############

        item = (MailItem)inboxFolder.Items[i];
        // item = inboxFolder.Items[i];
        if (item.Body != "")
        {
            if ((item.Body.Contains("Box Number =")) && (item.Body.Contains("Contract ID = ")) && (item.Body.Contains("Branch = ")) && (item.Body.Contains(currentFile.Replace('_', '/'))))
            {
                //    matchFound = true;
                MailStack current = new MailStack();
                Console.WriteLine("________________________");
                Console.WriteLine("File matched \t\t:\t" + currentFile + ".tif");

我环顾四周,但无法理解可用的答案。

任何帮助表示赞赏。

4

1 回答 1

3

试试这个...

item = inboxFolder.Items[i] as MailItem;
if (item != null) 
{ 
   // ...
}
于 2012-06-07T13:07:54.233 回答