2015-12-02 141 views
0

我想上傳一個JSON文件到任何GDrive的根文件夾。我已經通過Google搜索全部答案,並嘗試自行解決問題。無論我做了什麼request.Responsebody總是返回null。在這裏我試圖做一個空白的.txt文件(它仍然不起作用)。無法上傳到谷歌驅動器

這是獲取憑證的代碼,然後它將生成的DeviceService設置爲變量。

//GDrive Cred 
public static void GetCred() 
{ 
    //Get Credential 
    UserCredential credential; 

    using (var stream = 
     new FileStream(Path + "\\client_secret.json", FileMode.Open, FileAccess.Read)) 
    { 
     string credPath = System.Environment.GetFolderPath(
      System.Environment.SpecialFolder.Personal); 
     credPath = System.IO.Path.Combine(credPath, ".credentials/drive-dotnet-quickstart"); 

     credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
      GoogleClientSecrets.Load(stream).Secrets, 
      Scopes, 
      "user", 
      CancellationToken.None, 
      new FileDataStore(credPath, true)).Result; 
     Console.WriteLine("Credential file saved to: " + credPath); 
    } 

    // Create Drive API service. 
    var service = new DriveService(new BaseClientService.Initializer() 
    { 
     HttpClientInitializer = credential, 
     ApplicationName = ApplicationName, 
    }); 

    mService = service; 
} 

這是上傳文件的代碼。

//Save JSON to GDrive 
public static void SaveJSONtoDrive() 
{ 

    GetCred(); 
    // File's metadata. 
    Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); 
    body.Title = "ATGEntries.txt"; 
    body.Description = "Database JSON for Adventurer's Tour Guide"; 
    //body.MimeType = "application/json"; 
    body.MimeType = "text/plain"; 
    body.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } }; 

    // File's content. 
    byte[] byteArray = System.IO.File.ReadAllBytes(Path + "\\ATGEntries.txt"); 
    MemoryStream stream = new MemoryStream(byteArray); 
    try 
    { 
     FilesResource.InsertMediaUpload request = mService.Files.Insert(body, stream, "text/plain"); 
     request.UploadAsync(); 

     Google.Apis.Drive.v2.Data.File file = request.ResponseBody; 

     // Uncomment the following line to print the File ID. 
     Console.WriteLine("File ID: " + file.Id); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine("An error occurred: " + e.Message); 

    } 
} 

有人可以試圖幫助我解決這個奇怪的錯誤嗎?

回答

0

我不能相信這不是任何地方,所以我會回答我自己的問題,希望它能幫助別人。

,請注意行,你以後設置「credPath」變量

確保部分「.credentials /」必須是相同的名稱,無論你在一個名爲您的OAuth 2.0客戶端ID Google Developers Console。這應該解決這個問題。

相關問題