简体   繁体   English

如何使用 c# 和 Google API 在 Google 日历中创建事件?

[英]How to create an event in Google Calendar using c# and Google API?

UPDATE: I solved this problem and posted the solution as an answer below!更新:我解决了这个问题并在下面发布了解决方案作为答案! ;) ;)

I need to create an event and add it to Google Calendar using Google API.我需要创建一个事件并使用 Google API 将其添加到 Google 日历。

For now I only know how to get all the events I have from Google Calendar.目前我只知道如何从 Google 日历中获取我拥有的所有活动。 This is what I've got so far:这是我到目前为止所得到的:

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 CalendarQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/calendar-dotnet-quickstart.json
        static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
        static string ApplicationName = "Google Calendar API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.MaxResults = 10;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = request.Execute();
            Console.WriteLine("Upcoming events:");
            if (events.Items != null && 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.");
            }
            Console.Read();
        }
    }
}

What I am trying to do must be looking something like this:我正在尝试做的必须看起来像这样:

        var ev = new Event();
        EventDateTime start = new EventDateTime();
        start.DateTime = new DateTime(2019, 3, 11, 10, 0, 0);

        EventDateTime end = new EventDateTime();
        end.DateTime = new DateTime(2019, 3, 11, 10, 30, 0);


        ev.Start = start;
        ev.End = end;
        ev.Description = "Description...";

        events.Items.Insert(0, ev);

I've spent the entire day searching any .NET samples but got nothing.我花了一整天的时间搜索任何 .NET 示例,但一无所获。 Any help appreciated!任何帮助表示赞赏! ;) ;)

I've solved this problem!我已经解决了这个问题! So before building the project change所以在构建项目之前改变

static string[] Scopes = { CalendarService.Scope.CalendarReadonly };

to

static string[] Scopes = { CalendarService.Scope.Calendar };

If you already built the solution then delete credentials.json file and then reload it.如果您已经构建了解决方案,则删除凭据.json文件,然后重新加载它。 The code for adding an event is here:添加事件的代码在这里:

    var ev = new Event();
    EventDateTime start = new EventDateTime();
    start.DateTime = new DateTime(2019, 3, 11, 10, 0, 0);

    EventDateTime end = new EventDateTime();
    end.DateTime = new DateTime(2019, 3, 11, 10, 30, 0);


    ev.Start = start;
    ev.End = end;
    ev.Summary = "New Event";
    ev.Description = "Description...";

    var calendarId = "primary";
    Event recurringEvent = service.Events.Insert(ev, calendarId).Execute();
    Console.WriteLine("Event created: %s\n", e.HtmlLink);

This is my first try with Google API so don't judge me ;) Hope it helps somebody one day!这是我第一次尝试使用 Google API,所以不要评判我 ;) 希望有一天能对某人有所帮助!

Note : You also need to remove the 'token.json' folder from \\bin\\debug folder注意:您还需要从 \\bin\\debug 文件夹中删除“token.json”文件夹

I try to do the same thing in this days I used your same code, but just in the first part (reading events) the system arise me an exception "System.InvalidOperationException: 'At least one client secrets (Installed or Web) should be set'" calling the method credential = GoogleWebAuthorizationBroker.AuthorizeAsync这几天我尝试做同样的事情,我使用了相同的代码,但就在第一部分(读取事件)中,系统出现了一个异常“System.InvalidOperationException:'至少一个客户端机密(已安装或 Web)应该是set'" 调用方法 credential = GoogleWebAuthorizationBroker.AuthorizeAsync

Have somebody a solution for this issue?有人解决了这个问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM