我正在尝试找出一个程序(WinForms
)的visual basic .net 2008的代码,该代码可以上传和下载我的google云端硬盘帐户中的某些文件。
答案 0 :(得分:5)
花了很长时间才找到一些有效的代码,我从来没有找到任何用vb.net编写的代码。我发现的一切都是为C#编写的。在做了一堆转换后,我得到了一些工作。然而它很少,我不得不弄清楚剩下的。因此,为了让其他人的生活变得如此简单,可以使用适用于Drive v2&的vb.net代码。 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
如果您不知道下载文件的网址,那么您可以使用此代码获取一个:
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
我很累,并且现在不在乎清理代码,但是这样可以帮助您入门。快乐的节目!
答案 1 :(得分:0)