优化用于在Outlook加载项中搜索电子邮件的代码

时间:2014-07-16 11:18:02

标签: c# outlook

我有下一个将特定电子邮件信息打印到Excel文件的解决方案。我选择在日期中写入哪些电子邮件。

    [STAThread]
    public void Summary(DateTime startDate, DateTime finishDate, string fileSaveAdress)
    {
        try
        {
            Outlook.Application oApp = new Outlook.Application();
            Outlook.NameSpace oNs = oApp.GetNamespace("mapi");
            oNs.Logon(Missing.Value, Missing.Value, false, false);

            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(Missing.Value);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            Outlook.MAPIFolder pickedFolder = oApp.Session.PickFolder();
            Outlook.Items pickedFolderItems = pickedFolder.Items;

            int iX = 1;
            int iY = 1;
            int iAdjustColomn = 0;

            foreach (object obj in pickedFolderItems)
            {
                if (obj is Outlook.MailItem)
                {
                    Outlook.MailItem oMsg = (Outlook.MailItem)obj;
                    if (oMsg.ReceivedTime.ToUniversalTime() > startDate.ToUniversalTime() &&
                        oMsg.ReceivedTime.ToUniversalTime() < finishDate.ToUniversalTime())
                    {
                        xlWorkSheet.Cells[iY, iX] = oMsg.ReceivedTime.ToShortDateString() + " " +
                                                    oMsg.ReceivedTime.ToShortTimeString();
                        xlWorkSheet.Cells[iY, ++iX] = oMsg.Sender.Name;

                        for (int i = 1; i <= oMsg.Recipients.Count; i++)
                        {
                            xlWorkSheet.Cells[iY, ++iX] = oMsg.Recipients[i].Name;
                        }

                        xlWorkSheet.Cells[iY, ++iX] = oMsg.Subject;

                        Outlook.Attachments AttachmentArray = oMsg.Attachments;
                        if (AttachmentArray.Count != 0)
                        {
                            foreach (Outlook.Attachment attachment in AttachmentArray)
                            {
                                xlWorkSheet.Cells[iY, ++iX] = attachment.DisplayName;
                            }
                        }

                        iAdjustColomn += iX;

                        iY += 2;
                        iX = 1;
                    }
                }
            }

            for (int i = 1; i < iAdjustColomn; i++)
            {
                AutoFitColumn(xlWorkSheet, i);
            }

            xlWorkBook.SaveAs(fileSaveAdress, Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                              Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            xlWorkBook.Close(true, Missing.Value, Missing.Value);
            xlApp.Quit();

            oNs.Logoff();
        }
        catch (Exception e)
        {
            ErrorReport er = new ErrorReport(e.Message);
            er.ShowDialog();
        }
    }

主要问题是它给出了一个没有足够内存工作的错误。如何优化呢?请帮忙!

1 个答案:

答案 0 :(得分:1)

我会使用计数器替换使用Outlook对象和for循环的foreach调用。对于Outlook数据,使用foreach通常是一种不好的做法。

此外,更快的方法是使用带有Folder.GetTable的Table对象,您可以在其中设置要为迭代检索的最小数量的列/字段,以最大限度地减少内存使用。

Microsoft的示例(http://msdn.microsoft.com/en-us/library/bb176423%28v=office.12%29.aspx):

Sub RemoveAllAndAddColumns()
'Declarations
Dim Filter As String
Dim oRow As Outlook.Row
Dim oTable As Outlook.Table
Dim oFolder As Outlook.Folder

'Get a Folder object for the Inbox
Set oFolder = Application.Session.GetDefaultFolder(olFolderInbox)

'Define Filter to obtain items last modified after May 1, 2005
Filter = "[LastModificationTime] > '5/1/2005'"
'Restrict with Filter
Set oTable = oFolder.GetTable(Filter)

'Remove all columns in the default column set
oTable.Columns.RemoveAll
'Specify desired properties
With oTable.Columns
    .Add ("Subject")
    .Add ("LastModificationTime")
    'PR_ATTR_HIDDEN referenced by the MAPI proptag namespace
    .Add ("http://schemas.microsoft.com/mapi/proptag/0x10F4000B")
End With

'Enumerate the table using test for EndOfTable
Do Until (oTable.EndOfTable)
    Set oRow = oTable.GetNextRow()
    Debug.Print (oRow("Subject"))
    Debug.Print (oRow("LastModificationTime"))
    Debug.Print (oRow("http://schemas.microsoft.com/mapi/proptag/0x10F4000B"))
Loop
End Sub