从驱动器下载文件

时间:2017-08-10 13:12:09

标签: vb.net file download google-drive-api

我想使用vb.net从google驱动器下载文件。 我有一个gridview,其中列出了我的所有文件存在于驱动器中,当我选择一个文件(在网格中)时,我下载它。 在不同的网站搜索后,我尝试这样做,但我有一个问题

这是我的代码

Public Sub DownloadFile(index As String)
    CreateService()
    Dim url As String = ""
    Dim list = Service.Files.List()
    ' list.Fields = "nextPageToken, items(id, title)"
    Dim count = list.Execute()
    For Each fich In count.Items
        If (fich.Title = index) Then
            url = fich.WebContentLink
            Exit For
        End If
    Next
    Dim Downloader = New MediaDownloader(Service)
    ' figure out the right file type base on UploadFileName extension
    Dim Filename = index
    Dim FileStream = New System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)
    Dim progress = Downloader.DownloadAsync(url, FileStream)
    If DownloadStatus.Downloading.Completed Then
        MessageBox.Show("succeful download")
    Else
        MessageBox.Show("erreur")
    End If

当消息框成功下载时,我在我的应用程序目录中找到该文件,但我无法打开它,他的大小是0KB

索引是行选择值(在网格中)

1 个答案:

答案 0 :(得分:1)

由于您首先使用异步下载方法,因此应使用前面的Await以确保在下载后执行方法的其余部分。 但是,您没有提供足够的代码来完全理解您的方法的过程以及还有什么可能是错的。

您应该按照此模式下载文件:https://developers.google.com/api-client-library/dotnet/guide/media_download

这是一个例子,不应按字面意思理解。您需要在方法中添加参数以填写APP_NAME_HERE,BUCKET_HERE,OBJECT_HERE,FILE_PATH_HERE。

Public Shared Sub DownloadFile()
    ' Create the service using the client credentials.
    Dim storageService = New StorageService(New 
    BaseClientService.Initializer() With
        {
            .HttpClientInitializer = credential,
            .ApplicationName = "APP_NAME_HERE"
        })
    ' Get the client request object for the bucket and desired object.
    Dim getRequest = storageService.Objects.Get("BUCKET_HERE", "OBJECT_HERE")
    Using fileStream As New System.IO.FileStream(
        "FILE_PATH_HERE",
        System.IO.FileMode.Create,
        System.IO.FileAccess.Write)
        ' Add a handler which will be notified on progress changes.
        ' It will notify on each chunk download and when the
        ' download is completed or failed.
        AddHandler getRequest.MediaDownloader.ProgressChanged, AddressOf Download_ProgressChanged
        getRequest.Download(fileStream)
    End Using
End Sub

Private Shared Sub  Download_ProgressChanged(IDownloadProgress progress)
    Console.WriteLine(progress.Status & " " & progress.BytesDownloaded);
End Sub

这是您使用Google Cloud API的方法,但您很可能想要使用Google Drive API:

Imports System.Net
Imports Google.Apis.Authentication
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data

Public Class MyClass

    ''' <summary>
    ''' Download a file and return a stream with its content.
    ''' </summary>
    ''' <param name="authenticator">
    ''' Authenticator responsible for creating authorized web requests.
    ''' </param>
    ''' <param name="file">Drive File instance.</param>
    ''' <returns>File's content if successful, null otherwise.</returns>
    Public Shared Function System.IO.Stream DownloadFile(authenticator As IAuthenticator, webFile As File)

        If Not String.IsNullOrEmpty(webFile.DownloadUrl) Then
            Try
                Dim request = WebRequest.Create(New Uri(webFile.DownloadUrl))
                authenticator.ApplyAuthenticationToRequest(request)
                Dim response = request.GetResponse()
                If response.StatusCode = HttpStatusCode.OK Then
                    Return response.GetResponseStream()
                End If

                Console.WriteLine("An error occurred: " & response.StatusDescription)
                Return null

            Catch (e as Exception)
                Console.WriteLine("An error occurred: " & e.Message)
                Return null
            End Try
        End If

        ' The file doesn't have any content stored on Drive.
        Return null;
    End Function
End Class

你所拥有的非常接近,这些改变应该能够发挥作用。

Public Sub DownloadFile(service As DriveService, fileName As String, outputStream As Stream)
    Dim list = service.Files.List().Execute()
    Dim file = list.FirstOrDefault(Function(x) x.Title.Equals(fileName))
    If file Is Nothing Then
        Console.WriteLine("File not found.")
        Return
    End If
    Dim request = service.Files.Get(file.Id)

    ' Add a handler which will be notified on progress changes.
    ' It will notify on each chunk download and when the
    ' download is completed or failed.
    AddHandler request.MediaDownloader.ProgressChanged,
            Sub(IDownloadProgress progress)
                Select Case progress.Status
                    Case DownloadStatus.Downloading
                        Console.WriteLine(progress.BytesDownloaded)

                    case DownloadStatus.Completed
                        Console.WriteLine("Download complete.")

                    Case DownloadStatus.Failed:
                        Console.WriteLine("Download failed.")

                End Select
            End Sub
        request.Download(outputStream);
End Sub