首页 文章

如果Asp.net中的Google Cloud 端硬盘中不存在该文件夹,请创建该文件夹

提问于
浏览
0

我正在Asp.net MVC中创建一个应用程序,我想在谷歌驱动器上传文件 . 以下代码成功创建新文件夹并将文件保存在该文件夹中:

public void Upload(string fileName, byte[] bytes)
        {
            if (_userCredential != null)
            {
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = _userCredential,
                    ApplicationName = "Test App"
                });

                var file = new File { Title = "Test folder", MimeType = "application/vnd.google-apps.folder" };
                var result = service.Files.Insert(file).Execute();
                var saveresult = result.Id;

                Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
                body.Title = fileName;
                body.Description = "A test document";
                body.MimeType = "application/zip";
                body.Parents = new List<ParentReference>() { new ParentReference() { Id = saveresult } };
                var stream = new System.IO.MemoryStream(bytes);
                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
                request.Upload();
                if (request.ResponseBody == null)
                {
                    throw new Exception("User remove access to aplication.");
                }
            }
        }

现在问题是在我尝试再次保存文件后保存文件一次它创建另一个文件夹并将文件保存在该文件夹中但是我想检查文件夹是否存在而不是将文件保存在该文件夹中以及文件夹不存在比首先创建文件夹而不是保存该文件 . 谢谢 .

1 回答

  • 0

    你可以查看更多details.

    using Google.Apis.Drive.v2;
    using Google.Apis.Drive.v2.Data;
    
    // ...
    
    public class MyClass {
    
    // ...
    
    /// <summary>
    /// Print files belonging to a folder.
    /// </summary>
    /// <param name="service">Drive API service instance.</param>
    /// <param name="folderId">ID of the folder to print files from</param>
    public static void PrintFilesInFolder(DriveService service,
      String folderId) {
    ChildrenResource.ListRequest request = service.Children.List(folderId);
    
    do {
      try {
        ChildList children = request.Execute();
    
        foreach (ChildReference child in children.Items) {
          Console.WriteLine("File Id: " + child.Id);
        }
        request.PageToken = children.NextPageToken;
      } catch (Exception e) {
        Console.WriteLine("An error occurred: " + e.Message);
        request.PageToken = null;
      }
      } while (!String.IsNullOrEmpty(request.PageToken));
      }
    
      // ...
    
      }
    

相关问题