Outlook Interop c# sort items not working

↘锁芯ラ 提交于 2019-12-11 02:22:12

问题


I have stumbled upon a problem where the Outlook items table sort method does not give desired results - despite the ascending or descending the method GetLast() always returns the same email item. Code as follows:

Application olApp = new Application();
NameSpace olNS = olApp.GetNamespace("MAPI");
MAPIFolder oFolder = olNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

Explorer oExp = oFolder.GetExplorer(false);
//olNS.Logon( false, true);

result = new IOActionResult(null);

oFolder.Items.Sort("[ReceivedTime]");

var subject = oFolder.Items.GetLast().Subject;

I have tried specifying following:

oFolder.Items.Sort("[ReceivedTime]", true);
oFolder.Items.Sort("[ReceivedTime]", false);
oFolder.Items.Sort("[ReceivedTime]", OlSortOrder.olAscending);
oFolder.Items.Sort("[ReceivedTime]", OlSortOrder.olDescending);

Which did not seem to work either... Any thoughts appreciated!


回答1:


On your last line;

var subject = oFolder.Items.GetLast().Subject;

You are being returned a new Items object from Outlook, so your sort was actually performed on an instance that you no longer have a reference to.

Change your code to look like this;

Application  olApp = new Application();
NameSpace olNS = olApp.GetNamespace("MAPI");
MAPIFolder oFolder = olNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

Items items = oFolder.Items;
items.Sort("[ReceivedTime]");

var subject = items.GetLast().Subject;

A good rule of thumb when developing against Outlook is to always assign intermediary members of objects to their own local variable. This is particular relevant for releasing them later on.



来源:https://stackoverflow.com/questions/18337839/outlook-interop-c-sharp-sort-items-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!