Write a C# Application to Retrieve Calendar Items from Microsoft Exchange 2016 Using EWS

Introduction

I wanted to do the simplest thing I could to talk to EWS on Exchange 2016 Server (on premises) using C#. I’m going to show you step by step how I was able to pull a list of calendar appointments from calendar.

Creating a Project

First I launched Visual Studio 2022 and chose “Create a new project” from the opening menu as shown below.

Adding the Exchange Reference to the Project

Next we will get the NuGet package we need to be able to use EWS services from C#. I used the GUI NuGet package manager in Visual Studio.

using Microsoft.Exchange.WebServices.Data;
static void Main(string[] args)
{
var service = new ExchangeService(ExchangeVersion.Exchange2016);

service.Credentials = new WebCredentials("myuserid", "mypassword");
service.Url = new Uri("https://clientaccess.mycorp.com/EWS/Exchange.asmx");

DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddDays(30);
const int NUM_APPTS = 10;
CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
// Set the start and end time and number of appointments to retrieve.
CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);
// Limit the properties returned to the appointment's subject, start time, and end time.
cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
// Retrieve a collection of appointments by using the calendar view.
DateTime startTime = DateTime.Now;
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
DateTime endTime = DateTime.Now;
foreach (Appointment a in appointments)
{
Console.Write("Subject: " + a.Subject.ToString() + " ");
Console.Write("Start: " + a.Start.ToString() + " ");
Console.Write("End: " + a.End.ToString());
Console.WriteLine();
}
var timeToRun = endTime - startTime;
Console.Write($"It took {timeToRun.TotalSeconds.ToString()} seconds to run...");
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lindsay Leeds

Lindsay Leeds

I am an IT guy by trade, with interests in investing and personal finance.