C# 从Google日历中删除事件
我想通过使用用户的电子邮件ID删除用户的谷歌日历事件 我尝试使用以下代码删除该事件C# 从Google日历中删除事件,c#,google-api,google-calendar-api,google-oauth,google-api-dotnet-client,C#,Google Api,Google Calendar Api,Google Oauth,Google Api Dotnet Client,我想通过使用用户的电子邮件ID删除用户的谷歌日历事件 我尝试使用以下代码删除该事件 CalendarService service = new CalendarService(); string calendarId = "primary"; service.Events.Delete(calendarId, eventId).Execute(); 但它给了我以下的例外 Google
CalendarService service = new CalendarService();
string calendarId = "primary";
service.Events.Delete(calendarId, eventId).Execute();
但它给了我以下的例外
Google.Apis.Requests.RequestError
Login Required [401]
Errors [
Message[Login Required] Location[Authorization - header] Reason[required] Domain[global]
]
如何做到这一点并避免出现异常?您不能只创建一个空的日历服务对象,它需要首先进行身份验证
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar Oauth2 Authentication Sample"
});
您必须使用Oauth2创建凭据才能访问用户日历
/// <summary>
/// This method requests Authentcation from a user using Oauth2.
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static CalendarService AuthenticateOauth(string clientSecretJson, string userName)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
string[] scopes = new string[] { CalendarService.Scope.CalendarReadonly, //View your calendars
CalendarService.Scope.Calendar}; //Manage your calendars
UserCredential credential;
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
return new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 account CalendarService failed" + ex.Message);
throw new Exception("CreateServiceAccountCalendarFailed", ex);
}
}
//
///此方法使用Oauth2向用户请求授权。
///凭据存储在System.Environment.SpecialFolder.Personal中
///文件https://developers.google.com/accounts/docs/OAuth2
///
///从Google开发者控制台到客户端机密json文件的路径。
///正在授权的用户的标识字符串。
///DriveService用于针对驱动器API发出请求
公共静态日历服务AuthenticateAuth(字符串clientSecretJson,字符串用户名)
{
尝试
{
if(string.IsNullOrEmpty(用户名))
抛出新的ArgumentNullException(“用户名”);
if(string.IsNullOrEmpty(clientSecretJson))
抛出新ArgumentNullException(“clientSecretJson”);
如果(!File.Exists(clientSecretJson))
抛出新异常(“clientSecretJson文件不存在。”);
//这些是您需要的权限范围。最好只请求您需要的权限,而不是所有权限
string[]scopes=新字符串[]{CalendarService.Scope.CalendarReadonly,//查看您的日历
CalendarService.Scope.Calendar};//管理您的日历
用户凭证;
使用(var stream=newfilestream(clientSecretJson,FileMode.Open,FileAccess.Read))
{
字符串credPath=System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath=Path.Combine(credPath,“.credentials/”,System.Reflection.Assembly.getExecutionGassembly().GetName().Name);
//请求身份验证或加载以前存储的用户名身份验证
credential=GoogleWebAuthorizationBroker.AuthorizationAsync(GoogleClientSecrets.Load(stream.Secrets),
范围,
用户名,
取消令牌。无,
新文件数据存储(credPath,true))。结果;
}
//创建驱动器API服务。
返回新的CalendarService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“日历Oauth2身份验证示例”
});
}
捕获(例外情况除外)
{
Console.WriteLine(“创建Oauth2帐户日历服务失败”+ex.Message);
抛出新异常(“CreateServiceAccountCalendarFailed”,ex);
}
}
从我的谷歌日历API样本项目中提取的代码在上面有更多的代码,以备您需要