使用c#访问公共Google日历
本文关键字:Google 日历 访问 使用 | 更新日期: 2023-09-27 17:50:28
我有一个WPF应用程序,其中我想访问我添加到我的Google帐户中的公共Google Calendar,以便查找即将发生的事件。我使用了谷歌提供的快速入门,但我不知道如何选择我想要访问的日历。如何选择从哪个日历获取事件?
UPDATE:将代码和解决方案移动到一个单独的答案
使用CalenderList API
获取日历列表。
根据文档:
日历列表-日历UI中用户日历列表中所有日历的列表。
往下滚动你会发现:
关于calendarList条目资源
用户日历列表中的日历是在Google日历web界面的"我的日历"或"其他日历"下可见的日历:
访问日历很简单!我只需要改变
中的primary
EventsResource.ListRequest request = service.Events.List("primary");
到我想要访问的日历的日历ID。现在我可以从我的主日历中获取我的事件了!
<标题>解决方案:public class GoogleCalendar
{
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
static string ApplicationName = "Calendar API Quickstart";
public static string GetEvents()
{
UserCredential credential = Login();
return GetData(credential);
}
private static string GetData(UserCredential credential)
{
// Create Calendar Service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("The calendar ID to the calender I want to access");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Console.WriteLine("Upcoming events:");
Events events = request.Execute();
if (events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0} ({1})", eventItem.Summary, when);
}
}
else
{
Console.WriteLine("No upcoming events found.");
}
return "See console log for upcoming events";
}
static UserCredential Login()
{
UserCredential credential;
using (var stream = new FileStream(@"Components'client_secret.json", FileMode.Open,
FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment
.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
return credential;
}
}
标题>