【问题标题】:Upload and download to Google Drive using VB.NET Form [closed]使用 VB.NET 表单上传和下载到 Google Drive [关闭]
【发布时间】:2013-03-26 20:14:44
【问题描述】:

我正在尝试找出一个程序 (WinForms) 的 Visual Basic .net 2008 代码,该程序可以向我的 Google Drive 帐户上传和下载一些文件。

有人可以帮助我吗?

【问题讨论】:

  • 到目前为止你尝试过什么?在来这里之前,您应该已经阅读了我确定 Google 已经提供并尝试过的文档。
  • Yatrix,我在这里和谷歌搜索了一段美好的时光。我只是一个对编程一无所知的业余爱好者。如果我在这里是因为我需要帮助。
  • 这个网站是面向那些知道如何编程的人。它旨在回答特定问题,而不是教某人如何编程。祝你好运,但你可能想先了解基础知识。
  • 嗨。看看这个链接。他们有一些 VB.NET 代码。 example-code.com/vbnet/googleDrive.asp

标签: vb.net winforms google-drive-api


【解决方案1】:

花了很长时间才找到一些有效的代码,但我从未找到任何用 vb.net 编写的代码。我发现的所有内容都是为 C# 编写的。好吧,在做了一堆转换之后,我能够让一些事情正常工作。然而,它很少,我必须弄清楚其余的。因此,为了让其他人的生活更轻松,这里正在为 Drive v2 和 OAuth 2.0 工作 vb.net 代码:

    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

如果您不知道下载文件的 URL,那么您可以使用以下代码获取:

    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

【讨论】:

    【解决方案2】:

    请查看下面的 Google Drive SDK 网站上的 .NET 示例。

    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();
    
            }
        }
    }
    

    希望对你有所帮助。

    【讨论】:

    • 如果您可以在答案本身中包含文档的相关部分,那将非常有帮助。
    • 没有帮助,因为文档不支持 VB.Net
    • True - 但是转换器不能很好地处理快速启动示例。它破坏了service 的内联初始化,添加了一个令人困惑的变量Key(只需删除“键”并保留句点。)此外,示例使用var 而不是导致混淆的隐式类型。我真希望 Google 会花一点精力来支持所有 API 的 .Net 示例的 VB.Net 版本。 C# 和 VB.Net 在此类代码中存在显着差异。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多