I’m working on a C# project and need help with adding new events to Google Calendar through the API. Right now I can successfully retrieve existing events but I’m stuck on the creation part.
Here’s my current working code for reading events:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace MyCalendarApp
{
class CalendarManager
{
static string[] AccessScopes = { CalendarService.Scope.CalendarReadonly };
static string AppName = "My Calendar Application";
static void Main(string[] args)
{
UserCredential userCreds;
using (var fileStream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string tokenPath = "access_token.json";
userCreds = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(fileStream).Secrets,
AccessScopes,
"current_user",
CancellationToken.None,
new FileDataStore(tokenPath, true)).Result;
Console.WriteLine("Token saved to: " + tokenPath);
}
var calendarService = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = userCreds,
ApplicationName = AppName,
});
EventsResource.ListRequest listRequest = calendarService.Events.List("primary");
listRequest.TimeMin = DateTime.Now;
listRequest.ShowDeleted = false;
listRequest.SingleEvents = true;
listRequest.MaxResults = 15;
listRequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Events calendarEvents = listRequest.Execute();
Console.WriteLine("Found events:");
if (calendarEvents.Items != null && calendarEvents.Items.Count > 0)
{
foreach (var item in calendarEvents.Items)
{
string timeString = item.Start.DateTime.ToString();
if (String.IsNullOrEmpty(timeString))
{
timeString = item.Start.Date;
}
Console.WriteLine("{0} at {1}", item.Summary, timeString);
}
}
else
{
Console.WriteLine("No events available.");
}
Console.ReadLine();
}
}
}
I’m trying to implement something like this for creating events:
var newEvent = new Event();
EventDateTime startTime = new EventDateTime();
startTime.DateTime = new DateTime(2024, 5, 15, 14, 30, 0);
EventDateTime endTime = new EventDateTime();
endTime.DateTime = new DateTime(2024, 5, 15, 16, 0, 0);
newEvent.Start = startTime;
newEvent.End = endTime;
newEvent.Summary = "Meeting with team";
newEvent.Description = "Weekly project update";
// How do I actually save this to Google Calendar?
I’ve been looking through documentation but can’t find clear examples for .NET. What’s the proper way to insert this event into the calendar? Do I need different permissions or additional API calls?