Home > Mobile >  Visual basic Dot Net
Visual basic Dot Net

Time:09-26

I don't hit any error with below code but the file is not uploaded into google drive. Anything that i've missed? Please help.

NOTE: cred.json is the file generated from google developer console.

Dim Service As New DriveService

Dim cred As Google.Apis.Auth.OAuth2.GoogleCredential

Dim UploadRequest As FilesResource.CreateMediaUpload

Dim body As New Data.File()

cred = GoogleCredential.FromFile("D:\cred.json")
      
cred.CreateScoped(DriveService.Scope.Drive)

Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = cred})

body.Name = IO.Path.GetFileName("D:\Test.txt")

body.MimeType = "text/plain"

 Using Stream = New FileStream("D:\Test.txt", FileMode.Open)

         UploadRequest = Service.Files.Create(body, Stream, body.MimeType)

         UploadRequest.SupportsAllDrives = True

         UploadRequest.Upload()
End Using
  

CodePudding user response:

Its been a while since I have used vb .net sorry it took so long. This example should show you how to properly load the service account key file and upload your file to a directory of your choice.

Just remember to share the folder with the service account email address. If you open the json key file its the only variable that has an @ in it.

Imports System
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v3
Imports Google.Apis.Drive.v3.Data
Imports Google.Apis.Services
Imports Google.Apis.Upload

Module Program
     Sub Main(args As String())
        Console.WriteLine("Hello World!")
        
        REM path to your service account key file. 
        Const  pathToServiceAccountKeyFile = "C:\Development\FreeLance\GoogleSamples\Credentials\ServiceAccountCred.json"

        REM load the service account credentials and use drive scope 
        Dim credential = GoogleCredential.FromFile(pathToServiceAccountKeyFile).CreateScoped(DriveService.Scope.Drive)
         
        Rem Create the drive service 
        Dim service = new DriveService(new BaseClientService.Initializer() with { 
                                          .HttpClientInitializer = credential
                                          })
         Task.Run(Async Function()
             Await UploadFileAsync(service)
         End Function).GetAwaiter().GetResult()
        
    End Sub
     
     Private Async Function UploadFileAsync(service As DriveService) As Task(Of Boolean)
        
         Const FilePath As String = "C:\Development\FreeLance\GoogleSamples\Data\dummy.txt"
         
         Dim plist As List(Of String) = New List(Of String)

         REM Folder id to upload the file To
         Const idFolderSave = "0B5pJkOVaKccEYm5pVTJCWGFJbGM"
        
         plist.Add(idFolderSave) 'Set parent folder

         If (System.IO.File.Exists(FilePath)) Then
             Dim fileMetadata = New File() With {
                     .Name = "Test",
                     .MimeType = "text/plain",
                     .Parents = plist
                     }

             Dim request As FilesResource.CreateMediaUpload

             Using stream = New System.IO.FileStream(FilePath, System.IO.FileMode.Open)
                 request = service.Files.Create(fileMetadata, stream, "text/plain")
                 request.Fields = "id, parents"
                 dim results = await request.UploadAsync()
                 
                 If (results.Status = UploadStatus.Failed)
                     Console.WriteLine("failed")
                     Console.WriteLine(results.Exception)
                     
                 else
                    Dim file As File = request.ResponseBody
                    Console.WriteLine("File upload: "   file.Id)
                 End If
                     
             End Using

            
         Else
             Console.WriteLine("File does not exist: "   FilePath)
         End If
     End Function
   
End Module

I will make sure to document this some where i dont think we currently have any visual basic samples any where for the library.

  • Related