Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
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?
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
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.
Related
In SSIS I am using a VB.NET script task to download a file from an FTP folder.
The script is the following
Imports System
Imports System.Data
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Public Class ScriptMain
Public Sub Main()
Dim objWebClient As WebClient = New WebClient()
Dim strDownloadURL As String = "ftp://mydownloadhosting.com/myfolder/" + Dts.Variables("GetDate").Value.ToString() + "_daily.xml"
Dim strFileName As String = Dts.Variables("WorkingFile").Value.ToString()
Dim wp As WebProxy = New WebProxy("my.proxy.local", 1234)
objWebClient.Proxy = wp
objWebClient.Credentials = New System.Net.NetworkCredential("username", "password")
objWebClient.DownloadFile(strDownloadURL, strFileName)
Dts.TaskResult = Dts.Results.Success
End Sub
End Class
it works correctly but my target is to manage the exception, in particular to discriminate between:
file not found
all other problems (timeout, problem with proxy, ...)
I have made some research about how to manage exception with WebClient() and I have found these:
How to catch 404 WebException for WebClient.DownloadFileAsync
How do I check a WebClient Request for a 404 error
Handling two WebException's properly
which they give different forms of the following:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
The main problem is that my code is in VB.NET and all the posted answered are written in C#, how can make a try/catch construct to handle an exception in my code?
An equivalent code in VB.NET is:
Try
' try to download file here
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
If DirectCast(ex.Response, HttpWebResponse).StatusCode = HttpStatusCode.NotFound Then
' // handle the 404 here
End If
ElseIf ex.Status = WebExceptionStatus.NameResolutionFailure Then
' handle name resolution failure
End If
End Try
Though the above/your code is for HTTP, not for FTP. FTP has different status codes.
For FTP, use:
FtpWebResponse and
FtpStatusCode.
For some FTP examples, see:
C#: How to check if file exists on FTP before FtpWebRequest
VB.NET: VB.net - see if remote file exists
There are many C# to VB.NET converters that you can refer to when you need to convert simple codes:
Telerik C#/VB.NET online code converter
Instant VB – Our C# to VB.NET Converter
The equivalent VB.NET code is:
Imports System
Imports System.Data
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Public Class ScriptMain
Public Sub Main()
Try
Dim objWebClient As WebClient = New WebClient()
Dim strDownloadURL As String = "ftp://mydownloadhosting.com/myfolder/" + Dts.Variables("GetDate").Value.ToString() + "_daily.xml"
Dim strFileName As String = Dts.Variables("WorkingFile").Value.ToString()
Dim wp As WebProxy = New WebProxy("my.proxy.local", 1234)
objWebClient.Proxy = wp
objWebClient.Credentials = New System.Net.NetworkCredential("username", "password")
objWebClient.DownloadFile(strDownloadURL, strFileName)
Dts.TaskResult = Dts.Results.Success
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
If (CType(ex.Response, HttpWebResponse)).StatusCode = HttpStatusCode.NotFound Then
'handle the 404 here
End If
ElseIf ex.Status = WebExceptionStatus.NameResolutionFailure Then
'handle name resolution failure
End If
Dts.TaskResult = Dts.Results.Failure
End Try
End Sub
End Class
I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})
I am trying to figure out how to use Google drive v3 resumable upload on vb.net to upload big files.
I've checked this https://developers.google.com/drive/v3/web/resumable-upload and was able to upload small files using basic upload but can't find any code samples for resumable upload using vb.net.
I managed to get it done, here's the final code in case somebody else needs:
Imports System.IO
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v3
Imports Google.Apis.Services
Imports Google.Apis.Upload
Imports Google.Apis.Util.Store
Module Module1
Dim credential As UserCredential
Dim ApplicationName As String = "NET"
Dim Scopes As String() = {DriveService.Scope.Drive}
Sub Main()
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
Dim service = New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
Task.Run(Async Function()
Await UploadFileAsync(service, credential.Token.AccessToken, "welcome.mp4", "video/mp4", DateTime.Now.ToString("HH:mm:ss tt"))
End Function).GetAwaiter().GetResult()
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
Private Async Function UploadFileAsync(service As DriveService, accessToken As String, filePath As String, mimeType As String, newFileName As String) As Task(Of Boolean)
Dim uri As Uri
Dim uploadStream = New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Using client = New HttpClient()
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken)
client.DefaultRequestHeaders.Add("X-Upload-Content-Type", mimeType)
client.DefaultRequestHeaders.Add("X-Upload-Content-Length", uploadStream.Length.ToString())
Dim request = New HttpRequestMessage(HttpMethod.Post, "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable")
request.Content = New StringContent("{""name"": """ + newFileName + """, ""parents"":[""folder_id_goes_here""]}")
request.Content.Headers.ContentType = New MediaTypeHeaderValue("application/json")
Dim response = Await client.SendAsync(request)
uri = response.Headers.Location
End Using
Dim uploader = ResumableUpload.CreateFromUploadUri(uri, uploadStream, New ResumableUploadOptions())
AddHandler uploader.ProgressChanged, AddressOf Upload_ProgressChanged
Dim progress As IUploadProgress
progress = Await uploader.UploadAsync()
If progress.Status <> UploadStatus.Completed Then
While (Await uploader.ResumeAsync()).Status <> UploadStatus.Completed
Await Task.Delay(10000)
End While
End If
uploadStream.Dispose()
Return True
End Function
Private Sub Upload_ProgressChanged(progress As IUploadProgress)
Console.WriteLine(progress.Status.ToString() & " " & progress.BytesSent)
End Sub
End Module
I want to upload txt files to my google drive using vb.net , I was searching for about a 2 hours and found this Upload and download to Google Drive using VB.NET Form
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
Can't get this code to work .. can someone help me fix this code or post here other working vb.net code?
Here is the code step by step:
1. Create a Console VB.NET app.
2. Install the NuGet package.
Open View > Other Windows > Package Manager Console and type:
Install-Package Google.Apis.Drive.v2
The output should look like:
PM> Install-Package Google.Apis.Drive.v2
...
Adding 'Google.Apis 1.9.2' to YourApp.
Successfully added 'Google.Apis 1.9.2' to YourApp.
Adding 'Google.Apis.Auth 1.9.2' to YourApp.
Successfully added 'Google.Apis.Auth 1.9.2' to YourApp.
Adding 'Google.Apis.Drive.v2 1.9.2.1940' to YourApp.
Successfully added 'Google.Apis.Drive.v2 1.9.2.1940' to YourApp.
PM>
3. Copy and paste the following code in Module1.vb:
Imports Google.Apis.Auth
Imports Google.Apis.Download
' Your original code was missing the following "Imports":
Imports Google.Apis.Drive.v2
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports System.Threading
Imports Google.Apis.Drive.v2.Data
Module Module1
' Call UploadFile(...) from your programs Main():
Sub Main()
UploadFile("C:\file_to_upload.txt")
End Sub
Private Service As DriveService = New DriveService
Private Sub CreateService()
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 Sub
Private Sub UploadFile(FilePath As String)
'Not needed from a Console app:
'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)
'' You were mmissing the Upload part!
UploadRequest.Upload()
Dim file As File = UploadRequest.ResponseBody
' Not needed from a Console app:
'Me.Cursor = Cursors.Default
MsgBox("Upload Finished")
End Sub
End Module
Do not forget to replace:
Path of file to upload.
Your client ID.
Your client secret.
Get your client ID and client secret here: https://console.developers.google.com/apis/credentials/oauthclient/
And that's it! Your file should appear on https://drive.google.com/drive/my-drive
It works!
TheFile.Title = "My document.txt"'I added extension.
TheFile.Description = "A test document"
TheFile.MimeType = ""'I left it blank,because type has been added before
I don't understand "client ID" but somehow I finished it after 30minutes of trying.
I am trying to get the Quickstart code for .Net imported to Visual Basic (VB .NET) and I had some errors. I am a newbie to this kind of programming. Would appreciate some pointers, or someone pointing out something that is fundamentally wrong with the code.
Appreciate the help!
The errors that I get when I try to compile the Console App are:
Error 2 Argument not specified for parameter 'arg' of 'Private Shared Function GetAuthorization(arg As Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient) As DotNetOpenAuth.OAuth2.IAuthorizationState'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 22 86 Nipod Drive Console
Error 3 'BaseClientService' is ambiguous in the namespace 'Google.Apis.Services'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 23 48 Nipod Drive Console
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports Google.Apis.Services
Namespace GoogleDriveSamples
Class DriveCommandLineSample
Shared Sub Main(ByVal args As String)
Dim CLIENT_ID As [String] = "YOUR_CLIENT_ID"
Dim CLIENT_SECRET As [String] = "YOUR_CLIENT_SECRET"
'' Register the authenticator and create the service
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization)
Dim service = New DriveService(New BaseClientService.Initializer() With { _
.Authenticator = auth _
})
Dim body As New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("document.txt")
Dim stream As New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
Console.WriteLine("File id: " + file.Id)
Console.WriteLine("Press Enter to end this process.")
Console.ReadLine()
End Sub
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState( New () {DriveService.Scopes.Drive.GetStringValue()})
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Console.Write(" Authorization Code: ")
Dim authCode As String = Console.ReadLine()
Console.WriteLine()
' Retrieve the access token by using the authorization code:
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
End Namespace
I reliase this is an old subject, but this may help someone in future, make sure you compile in framework 3.5
Sorry cant seem to edit or delete my previous answer, for anyone in future, this should help:
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports System.Security
Imports Google.Apis.Services
Public Class GoogleDrive
Public Function UploadFile() As Boolean
Const CLIENT_ID As String = "xxxxxxxxxxxxx.apps.googleusercontent.com"
Const CLIENT_SECRET As String = "-yyyyyyyyyyyyyyyyyyyyyyy"
'Register the authenticator and create the service
Dim provider As NativeApplicationClient = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim getAuth As Func(Of NativeApplicationClient, IAuthorizationState) = AddressOf GetAuthorization
Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, getAuth)
Dim service = New DriveService(New BaseClientService.Initializer() With {.Authenticator = auth})
Dim body As File = New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("D:\document.txt")
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
MessageBox.Show("File : " & file.Id)
End Function
Private Function GetAuthorization(ByVal Client As NativeApplicationClient) As IAuthorizationState
Dim RetVal As IAuthorizationState
Dim state As IAuthorizationState = New AuthorizationState(New String() {DriveService.Scopes.Drive.GetStringValue()})
'Check to see if we have a saved refresh token
If My.Settings.SavedAuth.ToString <> "" Then
state.RefreshToken = My.Settings.SavedAuth
If (Client.RefreshToken(state)) Then
Return state
End If
End If
'Get the auth URL:
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = Client.RequestUserAuthorization(state)
'Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
'wait until user has entered the code
Dim authCode As String = InputBox("Authorisation code", "Authorisation Code", "")
'Retrieve the access token by using the authorization code:
RetVal = Client.ProcessUserAuthorization(authCode, state)
'store the refresh token
Call StoreRefreshToken(state.RefreshToken)
Return RetVal
End Function
Private Function LoadRefreshToken() As String
Return My.Settings.SavedAuth
End Function
Private Sub StoreRefreshToken(ByVal Token As String)
My.Settings("SavedAuth") = Token
My.Settings.Save()
End Sub
End Class