按文件夹名称(C#)检查Google云端硬盘中是否存在文件夹

问题描述 投票:0回答:1

我初始化了Google API服务,并将该服务传递给Create文件夹方法,每次它在Google云端硬盘中创建相同的文件夹时,我都想应用逻辑如果文件夹存在,则不创建它,只需返回其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
1个回答
0
投票

由于文件名在Google驱动器中不是唯一的,因此我们必须找到文件名来确定文件名是否存在。这里是一个工作示例:

© www.soinside.com 2019 - 2024. All rights reserved.