How to upload the file to Google Drive and create a link to download in .Net

Hello All,

Today, I’ll talk about how to upload the file to Google Drive and generate a downloadable file link through .Net.

I am using VB.Net to do this. Create a console project or a windows form project in Visual Studio.

There is an important step to undertake, and that is to acquire the access of the Google Drive API through your Google Account. Below is the link that will guide you through the entire process of enabling the Drive UI API

How to Enable the Drive Platform

Make sure, that at the end you should have three details with you, which is required in the tutorial:

  1. Client ID
  2. Client Secret
  3. Project Name

GDRIVE.png

Next, make sure, you have the Google Drive API v3 with you if not, you can use Nuget to install the API for you.

Link: Nuget: Google Drive API V3

Through Package Manager Console: Install-Package Google.Apis.Drive.v3

Below is the list of MIME types, that can be used with Google Drive API. Please keep this handy for the rest of the tutorial:

File Type MIME
xls application/vnd.ms-excel
xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
xml text/xml
ods application/vnd.oasis.opendocument.spreadsheet
csv text/plain
tmpl text/plain
pdf application/pdf
php application/x-httpd-php
jpg image/jpeg
png image/png
gif image/gif
bmp image/bmp
txt text/plain
doc application/msword
js text/js
swf application/x-shockwave-flash
mp3 audio/mpeg
zip application/zip
rar application/rar
tar application/tar
arj application/arj
cab application/cab
html text/html
htm text/html
default application/octet-stream
folder application/vnd.google-apps.folder

After you ensure, that the API V3 package is deployed correctly, write the below import statements.

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

Declare a Drive Service Variable

Private moService As DriveService = New DriveService

TIP: Always re-initialize the Drive Service variable, before you upload. It took me a while to realise this 🙂

Next, create a method by the name CreateService, which will hold your Google Drive Client IDs and connect to your Project Name. You can copy the contents as it is, and reply the place holders, with your Client ID, Client Secret and Project Names respectively.

Private Sub CreateService()

Dim ClientId = “YOUR CLIENT ID HERE”
Dim ClientSecret = “YOUR CLIENT SECRET HERE”

Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientId, .ClientSecret = ClientSecret}, {DriveService.Scope.Drive}, “user”, CancellationToken.None).Result
moService = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = “YOUR PROJECT NAME HERE”})

End Sub

Next, we will be using a PDF file to upload into the drive, you can copy the below snippet into a method or a function, as you feel appropriate.

‘ Checking if the Service is still alive, if not create the service again.
If moService.ApplicationName <> “YOUR PROJECT NAME” Then CreateService()

Dim oGDriveFile As New File()

oGDriveFile.Name =  “” ‘ Set your File Name here.
oGDriveFile.Description =  “” ‘ Set a meaningful description, I had set the same name as my project name
oGDriveFile.MimeType = “application/pdf” ‘ You must set your MIME type carefully. Refer to the MIME table above

Dim bArrByteArray As Byte() = System.IO.File.ReadAllBytes(“”) ‘ Your File Path from where you would want to upload from.
Dim oStream As New System.IO.MemoryStream(bArrByteArray)

Dim oUploadRequest As FilesResource.CreateMediaUpload

oUploadRequest = moService.Files.Create(oGDriveFile, oStream, oGDriveFile.MimeType)

oUploadRequest.Fields = “id”
oUploadRequest.Alt = FilesResource.CreateMediaUpload.AltEnum.Json

oUploadRequest.Upload() ‘ <- The file upload happens here.

Dim oFile As File = oUploadRequest.ResponseBody

‘ Setting this permission will allow anyone having the link to directly download the file.
‘ Google Drive, will not show any login page to the user, while attempting to download the file.
‘ The below two blocks are imperative.
Dim permission As New Google.Apis.Drive.v3.Data.Permission()
permission.Type = “anyone”
permission.Role = “reader”
permission.AllowFileDiscovery = True

Dim request As PermissionsResource.CreateRequest = moService.Permissions.Create(permission, oFile.Id)
request.Fields = “id”
request.Execute()

If Not IsNothing(oFile) Then

sViewLink = ” https://drive.google.com/uc?id=&#8221; & oFile.Id  ‘ This is the link, that will be used to download the file.

Else
Cursor.Current = Cursors.Default
MessageBox.Show(“Unable to contact Google Drive. Check your Connection.”, “Title”, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Exit Sub
End If

And, that is it, your file is supposed to be uploaded to Google Drive, and a link will be available for any one to download. You can restrict the download of the file, by providing the emailaddress property of the file in the permission object. It seems to work only for the Google Email IDs only.

So, if you have any concerns or doubts on this tutorial, don’t hesitate to contact me through eMail or by posting a comment on this blog.

You can download the test file, using the below link.

DOWNLOAD THE TEST FILE HERE

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s