3

WinFormsGoogleドライブアカウントとの間でいくつかのファイルをアップロードおよびダウンロードできるプログラム()のVisual Basic.net2008のコードを理解しようとしています。

誰かが私を助けることができますか?

4

2 に答える 2

7

動作するコードを見つけるのに長い時間がかかり、vb.netで書かれたものは見つかりませんでした。私が見つけたものはすべてC#用に書かれています。たくさんの変換を行った後、私はいくつかのことを機能させることができました。しかし、それは非常に少なく、残りを理解する必要がありました。したがって、他の人の生活をとても楽にするために、ここではDrivev2とOAuth2.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
于 2014-09-17T05:55:36.690 に答える
2

下記のGoogleドライブSDKWebサイトにある.NETサンプルをご覧ください。

GoogleドライブSDKドキュメント

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

        }
    }
}

これがお役に立てば幸いです。

于 2013-03-26T20:22:18.137 に答える