使用MAPI操作Outlook时,Items.Sort按主题排序失效问题
尝试将指定Outlook文件夹中的邮件按主题升序排序,但调用MAPIFolder.Items.Sort方法后,邮件并未被排序。为验证该问题,我将邮件主题输出至Excel文件,尝试升序、降序及不调用Sort操作,输出顺序均无变化。
相关C#代码
using Microsoft.Office.Interop.Outlook; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; namespace DictionaryCollection_test_bed {//Namespace class Program {//Program static void Main(string[] args) {//Main //Open an Excel app to enter Outlook emails in the order they were processed Excel.Application xlTest = new Excel.Application(); Excel.Workbook xlWorkbookTest = xlTest.Workbooks.Open(sFilePath + "\\SepticTest.xlsx" ); Excel._Worksheet xlWorksheetTest = xlWorkbookTest.Sheets[1]; //Open the Outlook file Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application(); // Log in to Outlook NameSpace outlookNamespace = outlookApp.GetNamespace("MAPI"); outlookNamespace.Logon(); MAPIFolder OLAccount = outlookNamespace.Folders[sAccountName]; MAPIFolder OLFolder = OLAccount.Folders[sFolderName]; OLFolder.Items.Sort("[Subject]", false);//It makes no difference whether the second param is true or false //or Sort is omitted try {//Try int iRowCount = 1; // 修正:初始化变量 foreach (MailItem eMail in OLFolder.Items) { xlWorksheetTest.Cells[iRowCount, 1] = eMail.Subject; //Output to the test worksheet iRowCount += 1; } }//Try catch (System.Exception ex) //when (ex.Message.Contains("(E_NOINTERFACE)") == false) {//Catch // 可添加异常处理逻辑 }//Catch finally {//Finally xlWorkbookTest.Save(); xlWorkbookTest.Close(); xlTest.Workbooks.Close(); outlookNamespace.Logoff(); System.Runtime.InteropServices.Marshal.ReleaseComObject(outlookNamespace); System.Runtime.InteropServices.Marshal.ReleaseComObject(outlookApp); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorksheetTest); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbookTest); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlTest); }//Finally }//Main }//Program }//Namespace
输出示例(升序、降序、不排序结果一致)
FW: 57-4-2, 2620 EDENTON RD, , 2000 gal, 10/13/2023
FW: 57-5-2, 379 STREET RD, , 1750 gal, 10/18/2023
FW: 57-7-1.1, 149 CHEEK RD, , 1250 gal, 9/12/2023
FW: 57-7-22.2A, 130 WINDEMERE LA, , 1750 gal, 9/13/2023
FW: 57-8-23.2A, 170 SHERROCKEE LA, , 3000 gal, 9/14/2023
FW: APPROVED - HD - Sewage Permit, 10/12/202357-3-3, 5260 HOMEVILLE RD,
FW: 57-8-2.2, 409 PUSEY MILL RD, , 1250 gal, 10/18/2023
问题原因及解决方法
核心问题
Sort方法不会直接修改原Items集合,而是返回一个新的排序后的Items集合。原代码直接调用OLFolder.Items.Sort()但未接收返回值,后续遍历的还是未排序的原集合,所以排序不生效。
修正代码
将Sort的结果赋值给一个新的Items变量,然后遍历该变量:
// 替换原Sort调用代码 Items sortedItems = OLFolder.Items.Sort("[Subject]", false); // false=升序,true=降序 // 遍历排序后的集合 foreach (MailItem eMail in sortedItems) { xlWorksheetTest.Cells[iRowCount, 1] = eMail.Subject; iRowCount += 1; }
额外注意事项
- 原代码中
int iRowCount += 1;未初始化变量,需改为int iRowCount = 1;避免编译错误。 - try/catch关键字需小写(原代码中Try、Catch为大写,不符合C#语法规范)。
内容的提问来源于stack exchange,提问作者Charles Fleischmann

