2017-08-28 6 views
0

je cours ce code:fichier de téléchargement à conduire en utilisant google-drive-api et C#

private static string[] Scopes = { DriveService.Scope.DriveReadonly }; 
    private static string ApplicationName = "Drive API .NET Quickstart"; 
    private static string _folderId = "0B3s20ZXnD-M7dkdhZzZaeXZRTWc"; 
    private static string _fileName = "testFile"; 
    private static string _filePath = @"C:\Users\Yosi\Desktop\bla bla.rar"; 
    private static string _contentType = "application/zip"; 

    static void Main(string[] args) 
    { 
     Console.WriteLine("create cred"); 
     UserCredential credential = GetUserCredential(); 

     Console.WriteLine("Get Services"); 
     DriveService service = GetDriveService(credential); 

     Console.WriteLine("Upload File"); 
     UploadFileToDrive(service, _fileName, _filePath, _contentType); 

    } 


    private static UserCredential GetUserCredential() 
    { 
     using (var stream = new FileStream("client_secret.json", FileMode.OpenOrCreate, FileAccess.Read)) 
     { 
      string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); 
      credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json"); 

      return GoogleWebAuthorizationBroker.AuthorizeAsync(
       GoogleClientSecrets.Load(stream).Secrets, 
       Scopes, 
       "user1", 
       CancellationToken.None, 
       new FileDataStore(credPath, true)).Result; 
     } 
    } 

    private static DriveService GetDriveService(UserCredential credential) 
    { 
     return new DriveService(
      new BaseClientService.Initializer() 
      { 
       HttpClientInitializer = credential, 
       ApplicationName = ApplicationName, 
      }); 
    } 

    private static string UploadFileToDrive (DriveService service, string fileName, string filePath, string conentType) 
    { 
     var fileMatadata = new Google.Apis.Drive.v3.Data.File(); 
     fileMatadata.Name = fileName; 
     fileMatadata.Parents = new List<string> { _folderId }; 

     FilesResource.CreateMediaUpload request; 

     using (var stream = new FileStream(filePath, FileMode.Open)) 
     { 
      request = service.Files.Create(fileMatadata, stream, conentType); 
      request.Upload(); 
     } 

     var file = request.ResponseBody; 

     return file.Id; 


    } 
} 

et obtenir l'exception suivante:

enter image description here

quand je fais appel à la fonction: GetUserCredential();

Des idées ce qui peut causer l'erreur? En fait, je copie le code d'une vidéo mot par mot et je ne vois pas de raison logique pour cette erreur. La vidéo que j'ai utilisé: https://www.youtube.com/watch?v=nhQPwrrJ9kI&t=259s

+1

Copie possible de [Qu'est-ce qu'une exception NullReferenceException, et comment la réparer?] (Https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix -it) –

+0

avez-vous vérifié 'GoogleWebAuthorizationBroker' n'est pas nul? –

Répondre

1

Ce échoue:

GoogleClientSecrets.Load(stream).Secrets 

Vous pouvez générer le fichier en suivant les instructions ci-dessous si vous ne l'avez pas: https://github.com/jay0lee/GAM/wiki/CreatingClientSecretsFile

Assurez-vous que le fichier client_se cret.json existe dans votre dossier de candidature (où l'exe est) puis:

using (var stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
      "client_secret.json"), FileMode.OpenOrCreate, FileAccess.Read)) 

Bien sûr, ne pas inclure ce fichier lors du déploiement de l'application, chaque utilisateur doit avoir et copier leur propre fichier à l'application dossier.

1

Veuillez vérifier attentivement ce lien ci-dessous pour obtenir les références de l'utilisateur.

OAuth 2.0 - Credentials

ce code est par exemple:

private async Task Run() 
    { 
     UserCredential credential; 
     using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 
     { 
      credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
       GoogleClientSecrets.Load(stream).Secrets, 
       new[] { BooksService.Scope.Books }, 
       "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary")); 
     } 

     // Create the service. 
     var service = new BooksService(new BaseClientService.Initializer() 
      { 
       HttpClientInitializer = credential, 
       ApplicationName = "Books API Sample", 
      }); 

     var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync(); 
     ... 
    }