.NET: Get all Outlook calendar items

前端 未结 11 1351
情书的邮戳
情书的邮戳 2020-12-02 09:41

How can I get all items from a specific calendar (for a specific date). Lets say for instance that I have a calendar with a recurring item every Monday evening. When I requ

11条回答
  •  醉话见心
    2020-12-02 10:14

    I found this article very useful: https://docs.microsoft.com/en-us/office/client-developer/outlook/pia/how-to-search-and-obtain-appointments-in-a-time-range

    It demonstrates how to get calendar entries in a specified time range. It worked for me. Here is the source code from the article for your convenience :)

    using Outlook = Microsoft.Office.Interop.Outlook;
    
    private void DemoAppointmentsInRange()
    {
        Outlook.Folder calFolder = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar)
            as Outlook.Folder;
        DateTime start = DateTime.Now;
        DateTime end = start.AddDays(5);
        Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);
        if (rangeAppts != null)
        {
            foreach (Outlook.AppointmentItem appt in rangeAppts)
            {
                 Debug.WriteLine("Subject: " + appt.Subject 
                     + " Start: " + appt.Start.ToString("g"));
            }
        }
    }
    
    /// 
    /// Get recurring appointments in date range.
    /// 
    /// 
    /// 
    /// 
    /// Outlook.Items
    private Outlook.Items GetAppointmentsInRange(
        Outlook.Folder folder, DateTime startTime, DateTime endTime)
    {
        string filter = "[Start] >= '"
            + startTime.ToString("g")
            + "' AND [End] <= '"
            + endTime.ToString("g") + "'";
        Debug.WriteLine(filter);
        try
        {
            Outlook.Items calItems = folder.Items;
            calItems.IncludeRecurrences = true;
            calItems.Sort("[Start]", Type.Missing);
            Outlook.Items restrictItems = calItems.Restrict(filter);
            if (restrictItems.Count > 0)
            {
                return restrictItems;
            }
            else
            {
                return null;
            }
        }
        catch { return null; }
     }
    

提交回复
热议问题