2016-01-17 102 views
0

我一直在玩.NET Google Drive API,我可以通過API成功連接,驗證並獲取文件列表(我們的Google雲端硬盤中已經有數千個文件帳戶,通過網絡直接上傳)。通過API上傳到Google雲端硬盤的「禁止」錯誤

但是,在嘗試寫入數據時遇到了兩個非常類似的錯誤:如果我嘗試上載測試文件(test.txt),則出現403「禁止」錯誤。要創建一個新的文件夾給我一個類似的錯誤:

Exception thrown: 'Google.GoogleApiException' in Google.Apis.dll

Additional information: Google.Apis.Requests.RequestError

Insufficient Permission [403] Location[ - ] Reason[insufficientPermissions] Domain[global]

我已經遵循「快速入門」教程,以及其他類似的問題在這裏,但我看不出還有什麼我必須做的。這是我上傳文件的示例代碼;我需要在代碼或Google雲端硬盤帳戶本身中添加/更改哪些內容以允許上傳文件和創建文件夾?

class GDriveTest 
{ 
    static string[] Scopes = { DriveService.Scope.Drive,DriveService.Scope.DriveFile }; 
    static string ApplicationName = "Drive API .NET Quickstart"; 

    static void Main(string[] args) 
    { 
     UserCredential credential; 

     using (var stream = 
      new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) 
     { 
      string credPath = System.Environment.GetFolderPath(
       System.Environment.SpecialFolder.Personal); 
      credPath = 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, 
     }); 

     UploadSingleFile(service); 
    } 

    private static void UploadSingleFile(DriveService service) 
    { 
     File body = new File(); 
     body.Title = "My document"; 
     body.Description = "A test document"; 
     body.MimeType = "text/plain"; 

     byte[] byteArray = System.IO.File.ReadAllBytes("test.txt"); 
     System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); 

     FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain"); 
     request.Upload(); 

     File file = request.ResponseBody; 
     Console.WriteLine("File id: " + file.Id); 
     Console.ReadLine(); 
    } 
} 
+0

請爲UploadSingleFile添加代碼 – DaImTo

+0

@DaImTo:代碼已經在那裏了? – KenD

+1

哎呀對不起滾動條:/ – DaImTo

回答

1

問題可能範圍您請求

DriveService.Scope.DriveFile, // view and manage files created by this app 

嘗試

DriveService.Scope.Drive, // view and manage your files and documents 

我的代碼:

/// <summary> 
     /// Authenticate to Google Using Oauth2 
     /// Documentation https://developers.google.com/accounts/docs/OAuth2 
     /// </summary> 
     /// <param name="clientId">From Google Developer console https://console.developers.google.com</param> 
     /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param> 
     /// <param name="userName">The user to authorize.</param> 
     /// <returns>a valid DriveService</returns> 
     public static DriveService AuthenticateOauth(string clientId, string clientSecret, string userName) 
     { 
      if (string.IsNullOrEmpty(clientId)) 
       throw new Exception("clientId is required."); 
      if (string.IsNullOrEmpty(clientSecret)) 
       throw new Exception("clientSecret is required."); 
      if (string.IsNullOrEmpty(userName)) 
       throw new Exception("userName is required for datastore."); 


      string[] scopes = new string[] { DriveService.Scope.Drive}; 

      try 
      { 

       string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); 
       credPath = Path.Combine(credPath, ".credentials/Drive"); 

       // here 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(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } 
                          , scopes 
                          , userName 
                          , CancellationToken.None 
                          , new FileDataStore(credPath, true)).Result; 

       var service = new DriveService(new BaseClientService.Initializer() 
       { 
        HttpClientInitializer = credential, 
        ApplicationName = "Drive Authentication Sample", 
       }); 
       return service; 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.InnerException); 
       throw ex; 
      } 

     } 

/// <summary> 
     /// Insert a new file. 
     /// Documentation: https://developers.google.com/drive//v2/files/insert 
     /// </summary> 
     /// <param name="service">Valid authentcated DriveService</param> 
     /// <param name="body">Valid File Body</param> 
     /// <returns>File </returns> 
     public static File Insert(DriveService service, File body) 
     { 
      //Note Genrate Argument Exception (https://msdn.microsoft.com/en-us/library/system.argumentexception(loband).aspx) 
      try 
      { 
      return   service.Files.Insert(body).Execute(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("Request Failed " + ex.Message); 
       throw ex; 
      } 
     } 

    private static string GetMimeType(string fileName) 
     { 
      string mimeType = "application/unknown"; 
      string ext = System.IO.Path.GetExtension(fileName).ToLower(); 
      Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); 
      if (regKey != null && regKey.GetValue("Content Type") != null) 
       mimeType = regKey.GetValue("Content Type").ToString(); 
      return mimeType; 
     } 

執行

var driveService = StandardGoogleAuth.AuthenticateOauth("xxxxx.apps.googleusercontent.com", "uxpj6hx1H2N5BFqdnaNhIbie", "user"); 

       var uploadfileName = @"C:\Temp\test.txt"; 
       File body = new File(); 
       body.Title = System.IO.Path.GetFileName(uploadfileName); 
       body.Description = "File uploaded by Diamto Drive Sample"; 
       body.MimeType = GetMimeType(uploadfileName); 
       body.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } }; 

       // File's content. 
       byte[] byteArray = System.IO.File.ReadAllBytes(uploadfileName); 
       System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); 

      var result = FilesSample.Insert(driveService,body); 
+0

即使在將我的'string [] Scopes'改爲'DriveService.Scope.Drive'(而不是'.Drive'和'.DriveFiles')之後,我仍然會得到一個403 :( – KenD

+0

你是否改變了「用戶」來強制它請求新的範圍? – DaImTo

+0

我剛用我通常使用的代碼對它進行了測試它從我這裏工作我沒有看到它和你使用的代碼之間有太大的區別 – DaImTo

0

修改範圍將不會自動更新到TOKENRESPONSE用戶文件中。您必須重新生成該文件。

搜索「drive-dotnet-quickstart.json」並從其中刪除「Google.Apis.Auth.OAuth2.Responses.TokenResponse-user」。 然後運行您的代碼來重新生成該文件。

相關問題