Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload and download to Google Drive using VB.NET Form [closed]

I am trying to figure out the codes for visual basic .net 2008 of a program (WinForms) that could upload and download some files to and from my google drive account.

Someone can help me?

like image 736
John Smith Avatar asked Jan 29 '26 07:01

John Smith


2 Answers

It took a long time to find some code that worked and I never did find anything written in vb.net. Everything I found was written for C#. Well after doing a bunch of conversion I was able to get some things working. However it was very little and I had to figure out the rest. So to make other people's life so much easier here is working vb.net code for Drive v2 & OAuth 2.0:

    Imports System.Threading
    Imports System.Threading.Tasks

    Imports Google
    Imports Google.Apis.Auth.OAuth2
    Imports Google.Apis.Drive.v2
    Imports Google.Apis.Drive.v2.Data
    Imports Google.Apis.Services

    Imports Google.Apis.Auth
    Imports Google.Apis.Download

     'Dev Console:
     'https://console.developers.google.com/

     'Nuget command:
     'Install-Package Google.Apis.Drive.v2

    Private Service As DriveService = New DriveService

    Private Sub CreateService()
    If Not BeGreen Then
        Dim ClientId = "your client ID"
        Dim ClientSecret = "your client secret"
        Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientId, .ClientSecret = ClientSecret}, {DriveService.Scope.Drive}, "user", CancellationToken.None).Result
        Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = "Google Drive VB Dot Net"})
    End If
End Sub


    Private Sub UploadFile(FilePath As String)
    Me.Cursor = Cursors.WaitCursor
    If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()

    Dim TheFile As New File()
    TheFile.Title = "My document"
    TheFile.Description = "A test document"
    TheFile.MimeType = "text/plain"

    Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
    Dim Stream As New System.IO.MemoryStream(ByteArray)

    Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)

    Me.Cursor = Cursors.Default
    MsgBox("Upload Finished")
End Sub

    Private Sub DownloadFile(url As String, DownloadDir As String)
    Me.Cursor = Cursors.WaitCursor
    If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()

    Dim Downloader = New MediaDownloader(Service)
    Downloader.ChunkSize = 256 * 1024 '256 KB

    ' figure out the right file type base on UploadFileName extension
    Dim Filename = DownloadDir & "NewDoc.txt"
    Using FileStream = New System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)
        Dim Progress = Downloader.DownloadAsync(url, FileStream)
        Threading.Thread.Sleep(1000)
        Do While Progress.Status = TaskStatus.Running
        Loop
        If Progress.Status = TaskStatus.RanToCompletion Then
            MsgBox("Downloaded!")
        Else
            MsgBox("Not Downloaded :(")
        End If
    End Using
    Me.Cursor = Cursors.Default
End Sub

If you don't know the URL to download the file, then you can use this code to get one:

    Dim Request = Service.Files.List()
    Request.Q = "mimeType != 'application/vnd.google-apps.folder' and trashed = false"
    Request.MaxResults = 2
    Dim Results = Request.Execute
    For Each Result In Results.Items
        MsgBox(Result.DownloadUrl & vbCrLf & Result.Title & vbCrLf & Result.OriginalFilename)
    Next
like image 123
user1766329 Avatar answered Feb 03 '26 07:02

user1766329


Please look at the .NET samples found on the Google Drive SDK website found below.

Google Drive SDK Documentation

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DriveQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        static string[] Scopes = { DriveService.Scope.DriveReadonly };
        static string ApplicationName = "Drive API .NET Quickstart";

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

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                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,
            });

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine("{0} ({1})", file.Name, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();

        }
    }
}

Hope this helps you.

like image 43
Ryan Gunn Avatar answered Feb 03 '26 08:02

Ryan Gunn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!