Google Drive - How to interact and manage files

In this article I would like to give some information I collect from internet. 

 

Prerequisite

When you work with google services you need to follow some precautions. Google cares a lot about security and much more when try to access and manage data via coding. It is quite obvious that to access to files store in Google Drive you need to authenticate in some way.

Google asks you to do these steps:

  • 1.       Have a google account!!! Really? Doh!
  • 2.       Create a Project in the Google Cloud Platform
  • 3.       Create Credentials declaring the scope for which you’ll use them!

 

 

After these steps, you’ll be able to interact with Google services and in particular with Google Drive.

 

 

GCP Console – Google Cloud Platform Console

 

Search for the Google Cloud Platform page to perform all the actions to create Credentials we’ll need to do the requests 

 

Go to the link on the Google Identity page and click on the first link Google API Console

 

You’ll be redirect on this page:

 

 

Project Creation

 

From this page, through the first item (API and available services) you can Create your Project.

 

 

Credentials creation

To create Credentials you first have to configure the allow screen for OAuth. Select External User Type:

 

 

 

And set all requested data on the form of the application you use to interact with Google Drive

 

 

After this step,  go to Credentials and select Create Credentials 

 

 

And select “OAuth client ID” and then select Desktop Application if you’d like to use it in a .net desktop application.

 

 

After this step you’ll have only to set a name for this entry. The system will be back to you with client ID and client Secret and you have to copy these information into a file. Download also the json file to be sure to retrieve it in the future:

 

Now you have the two required information to perform requests to Google Drive of your account but before google may ask you to activate the API you need.

 

API and Enabled Services

 

Go to “ + Enable API and Services”

 

 

Search for Drive API and select it

 

 

Click on Manage (here the API is already active)

 

 

And then you can enable/disable the functionality

 

 

Run the Application

 

When your application is ready and runs Google will ask you to choose (or insert) the account to use for the scope.

 

 

 

You have to choose the account for which you create credentials under the relevant project.

After this step, your desktop application will also linked to that account and you’ll be able to manage files.

 

 

  

VB .Net – Manage Files on Google Drive - CODE

 

Add the relevant Google Drive Library Version from Project > Manage NuGet Packages…

 

 

After you download the library in your project you could see the references in the Solution Panel

 

 

Once you have downloaded the libraries you can use it.

 

The Service Manager Class

I used to create class to manage elements such as DataBase or other type of things. This is just what I do also to manage the Google Service.

So create a vb class in the solution and put code (I call it “gDriveMngr”) to:

-          Instantiate the service

-          Create the Service

-          Download a File

-          Delete a File

-          Upload a File

 

Import the relevant NameSpaces

Imports System.IO

Imports Google.Apis.Auth.OAuth2

Imports Google.Apis.Download

Imports Google.Apis.Drive.v3

Imports Google.Apis.Drive.v3.Data

Imports Google.Apis.Services

Imports System.Threading

 

Declaration of the class

Public Class gDriveMngr

 

    Some constant value for default credentials and credential filename  

    Const CL_ID As String = "<PUT_HERE_YOUR_DEFAULT_CLIENT_ID>"

    Const CL_SECRET As String = "<PUT_HERE_YOUR_DEFAULT_CLIENT_SECRET>"

    Const CRED_FILE As String = "\cred.txt"

 

    Declaration of the DriveService object – the one for which you can perform operations

    Dim gServ As DriveService

 

    Public Sub New()

        gServ = New DriveService

    End Sub

 

    This function is useful to create the service and know if everything is ok

    It is a boolean function True = Ok False = KO

    Public Function createService() As Boolean

 

        Dim bolRes = True  

        Dim credFile = ""

        credFile = Directory.GetCurrentDirectory() & CRED_FILE

 

        Dim clientID As String = ""

        Dim clientSecret As String = ""

        'if file does not exist default credentials will be used

        If (Not (System.IO.File.Exists(credFile))) Then

            MsgBox("Credential file not foud – Default value will be used", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Warning – Google Credential File Missing")

            clientID = CL_ID

            clientSecret = CL_SECRET

        Else

            'Read data from file using relative function

            clientID = ReadCredFile(credFile, "clientID")

            clientSecret = ReadCredFile(credFile, "clientSecret")

        End If

 

        If clientID.Length > 0 And clientSecret.Length > 0 Then

            Try

                Dim uc As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = clientID, .ClientSecret = clientSecret}, {DriveService.Scope.Drive}, "user", CancellationToken.None).Result

                gServ = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = uc, .ApplicationName = "<YourAppName>"})

            Catch

                bolRes = False

            End Try

        End If

 

        Return bolRes

 

    End Function

 

    Private Function ReadCredFile(nFile As String, strWhat As String)

        Dim strRes = ""

        Dim sr As New StreamReader(nFile)

        Dim line As String

 

        Do While sr.Peek() <> -1

 

            line = sr.ReadLine()

            If line.Split(New Char() {"="})(0) = strWhat Then

                strRes = line.Split(New Char() {"="})(1)

                Exit Do

            End If

        Loop

        sr.Close()

        sr = Nothing

 

        Return strRes

    End Function

 

    'Sub to upload a file passed as argument  

    'nFile is the path + filename

    Public Sub UpLoad(nfile As String)

 

        'Caricamento del file DB su Drive

        Dim myDriveFile As New Google.Apis.Drive.v3.Data.File

        Dim bArr As Byte() = System.IO.File.ReadAllBytes(nfile)

        Dim stream As New System.IO.MemoryStream(bArr)

        myDriveFile.Name = nfile.Split("\")(UBound(nfile.Split("\")))

        Dim uploadrequest As FilesResource.CreateMediaUpload

        Try

            uploadrequest = gServ.Files.Create(myDriveFile, stream, myDriveFile.MimeType)

            uploadrequest.Upload()

            Dim gFile As Google.Apis.Drive.v3.Data.File = uploadrequest.ResponseBody

            MsgBox("Upload succesfully done for file " & vbNewLine & "Name: " & gFile.Name & vbNewLine & "ID(entifier): " & gFile.Id, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Upload Result")

        Catch ex As Exception

            MsgBox("Exception: " & ex.Message)

        End Try

    End Sub

 

    Public Sub DeleteDriveFile(nFile As String)

        ‘Delete old file version

        Dim lstFiles As FileList

 

        Try

            lstFiles = gServ.Files.List().Execute()

            For Each f As Google.Apis.Drive.v3.Data.File In lstFiles.Files

                If f.Name = nFile Then

                    Dim delRequest As String

                    Try

                        delRequest = gServ.Files.Delete(f.Id).Execute()

                    Catch ex As Exception

                        MsgBox("Error during file deletion for " & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "DELETE ERROR ")

                    End Try

                End If

            Next

        Catch ex As Exception

            MsgBox("Exception: " & ex.Message)

        End Try

 

    End Sub

 

    Public Sub DownLoadFile(TmpLocalPath As String, nFile As String)

 

        Dim lstFiles As FileList

 

        Try

            lstFiles = gServ.Files.List().Execute()

            For Each f As Google.Apis.Drive.v3.Data.File In lstFiles.Files

                If f.Name = nFile Then

                    Dim dwnRequest As FilesResource.GetRequest = gServ.Files.Get(f.Id)

                    Try

                        Dim sr As New FileStream(TmpLocalPath & nFile, FileMode.Create)

                       

                        AddHandler dwnRequest.MediaDownloader.ProgressChanged,

                        Sub(progress As IDownloadProgress)

                            Select Case progress.Status

                                Case DownloadStatus.Downloading

                                    Console.WriteLine(progress.BytesDownloaded)

 

                                Case DownloadStatus.Completed

                                    Console.WriteLine("Download complete.")

 

                                Case DownloadStatus.Failed

                                    Console.WriteLine("Download failed.")

                            End Select

                        End Sub

                        dwnRequest.DownloadWithStatus(sr)

 

                    Catch ex As Exception

                        MsgBox("Download Error for " & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "DOWNLOAD ERROR")

                    End Try

 

                End If

            Next

        Catch ex As Exception

            MsgBox("Exception: " & ex.Message)

        End Try

 

    End Sub

 

 

 

End Class

   

After you create the class to manage drive file you can use it in your Main like this:

 

Dim gSrv As New gDriveMngr()

Const TmpLocalPath As String = "c:\temp\"

 

If Not (gSrv.createService()) Then

   MsgBox("Error in google service creation ", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Google Drive Service Error”)

 Else

   Dim strMyLocalFile As String = "c:\data\myfile.txt"

   Dim myFileName As String = strMyLocalFile.Split("\")(UBound(strMyLocalFile.Split("\")))

 

   gSrv.DownLoadFile(TmpLocalPath, myFileName)

 

   gSrv.DeleteDriveFile(myFileName)

 

   gSrv.UpLoad(strMyLocalFile)

      

 

End If