【发布时间】:2020-07-01 14:20:21
【问题描述】:
我初始化了 Google API 服务并将服务传递给 Create folder 方法,每次它在 Google Drive 中创建相同的文件夹时,我想应用逻辑如果文件夹存在,不要创建它,只返回它的 FolderID 否则创建新文件夹并返回其文件夹 ID。请提出建议。
var service= InitializeGoogleDriveAPIService(clientId, clientSecret);
var res=CreateFolder(service, "FolderName");
private static DriveService InitializeGoogleDriveAPIService(string clientId, string clientSecret)
{
string[] scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile, };
ClientSecrets clientSecrets = new ClientSecrets();
clientSecrets.ClientId = clientId;
clientSecrets.ClientSecret = clientSecret;
// Below is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("MyAppsToken")).Result;
//Once consent is received, the token will be stored locally on the AppData directory,
//so that next time we won't be prompted for consent. -one time setting for the Console app
BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.HttpClientInitializer = credential;
initializer.ApplicationName = "PRInvoices";
DriveService service = new DriveService(initializer);
service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
//Long Operations like file uploads might timeout. 100 is just precautionary value,
//can be set to any reasonable value depending on what you use your service for
return service;
}
public static string CreateFolder(DriveService service, string folderName)
{
var file = new Google.Apis.Drive.v3.Data.File { Name = folderName, MimeType = "application/vnd.google-apps.folder" };
// var RESILT = service.Files.List();
var result = service.Files.Create(file).Execute();
return result.Id;
}
【问题讨论】:
标签: c# api google-api google-drive-api google-drive-android-api