且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中检索交换Web服务中的2000多个邮件项目

更新时间:2023-08-31 21:49:34

如果你考虑你的代码在做什么,问题应该是显而易见的:当你试图检索它们时你正在移动消息。



考虑一个包含三条消息的简化示例,一次移动一条消息:

  1. 收件箱: [A,B,C] ;
  2. 检索邮件 0 A;
  3. A移至另一个文件夹;
  4. 收件箱: [B,C] ;
  5. 检索邮件 1 C
  6. C移至另一个文件夹;
  7. 收件箱: [B]
  8. 检索邮件 2 :错误





与修改集合的任何循环一样,你需要调整索引来考虑你的变化。

 做跨度> 
{
findMailItems = service.FindItems(findFolderItems.Folders [ 0 ]。Id,searchFilter,view);
if (findMailItems.TotalCount > 0
{
foreach var item in findMailItems.Items)
{
item.Move(folderId);
}
}

// 注意:不要更改view.Offset here!
}
while (findMailItems.MoreAvailable);


Hello all,
I have an inbox that contains 2068 mail items. I need to retreive all 2068 mails. But as per my code, this skips 1000 mails i.e initially it shows total count as 2068 and retrieves 1000 mails in the first loop and shows count as 1000 (pagesize=1000) but in second loop it shows the count as 68 and skips the 1000 mails and NextPageOffset is null. What am i doing wrong ?

What I have tried:

int pageSize = 1000;
FindFoldersResults findFolderItems = service.FindFolders(WellKnownFolderName.Inbox, sourceFolderFilter, new FolderView(1));
ItemView view = new ItemView(pageSize);
do
{
findMailItems = service.FindItems(findFolderItems.Folders[0].Id, searchFilter, view);                                
if (findMailItems.TotalCount > 0)
{
    foreach (var item in findMailItems.Items)
    {
         item.Move(folderId);
    }
}
view.Offset = findMailItems.NextPageOffset.Value;
}
 while (findMailItems.MoreAvailable);

If you consider what your code is doing, the problem should be obvious: you're moving the messages whilst you're trying to retrieve them.

Consider a simplified example with three messages, moving one at a time:
  1. Inbox: [ "A", "B", "C" ];
  2. Retrieve message 0: "A";
  3. Move "A" to another folder;
  4. Inbox: [ "B", "C" ];
  5. Retrieve message 1: "C"
  6. Move "C" to another folder;
  7. Inbox: ["B"]
  8. Retrieve message 2: Error



As with any loop which modifies the collection it's iterating over, you need to adjust the index to account for your changes.

do
{
    findMailItems = service.FindItems(findFolderItems.Folders[0].Id, searchFilter, view);
    if (findMailItems.TotalCount > 0)
    {
        foreach (var item in findMailItems.Items)
        {
            item.Move(folderId);
        }
    }
    
    // NB: Don't change the view.Offset here!
}
while (findMailItems.MoreAvailable);