//
type here
I need to sort the emails in a particular folder by Subject Ascending. Using Sort on the Folder does not sort the Items.
//To confirm this I have outputted the email Subject values to an Excel file and tried ascending, descending and no sorts but nothing makes a difference in the output order.
Here is the code and a subset of the output to show the lack of sorting. //C# Code 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 oprder 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 secod
//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 workseet
iRowCount += 1;
}
}//Try
{//Catch
catch (System.Exception ex) //when (ex.Message.Contains("(E_NOINTERFACE)") == false)
{//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
//Output sorted ascending, descending or not sorted
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
You are sorting one collection, and showing the elements of a completely different collection - every time you call
MAPIFolder.Items, you get back a brand newItemscollection that has no knowledge of any other instances of that object.Store
MAPIFolder.Itemsin a dedicated variable, sort it, then loop through it.