2016-01-22 102 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)); 
    } 

    // ... 

    } 
相關問題