2016-01-22 82 views
0

我在Asp.net MVC中创建一个应用程序,我想在谷歌驱动器上传文件。下面的代码成功地创建一个新的文件夹并将文件保存在该文件夹中:创建文件夹,如果它不存在于谷歌驱动器在Asp.net

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."); 
       } 
      } 
     } 

现在的问题是储蓄,一旦当我试图保存文件的文件后,它再次创造另一个文件夹,保存在文件中该文件夹,但我想检查,如果文件夹存在比它保存在该文件夹中的文件,并且如果该文件夹不存在比它首先创建一个文件夹,而不是保存该文件。 谢谢。

回答

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)); 
    } 

    // ... 

    }