【问题标题】:How to Download file from Google drive in WPF - installed application如何在 WPF 中从 Google 驱动器下载文件 - 已安装的应用程序
【发布时间】:2014-06-24 12:40:37
【问题描述】:

我正在开发 WPF 应用程序,在此我正在实现具有上传和下载功能的 Google Drive API。上传工作正常,但我在下载文档时遇到问题。我在https://developers.google.com/drive/web/manage-downloads查看了谷歌文档中的代码

 public static System.IO.Stream DownloadFile(IAuthenticator authenticator, File file) 
 {
   if (!String.IsNullOrEmpty(file.DownloadUrl)) 
   {
     try {
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(file.DownloadUrl));
       authenticator.ApplyAuthenticationToRequest(request);
       HttpWebResponse response = (HttpWebResponse) request.GetResponse();
       if (response.StatusCode == HttpStatusCode.OK) 
       {
          return response.GetResponseStream();
       }
       else
       {
          Console.WriteLine("An error occurred: " + response.StatusDescription);
          return null;
       }
    }
    catch (Exception e) 
    {
      Console.WriteLine("An error occurred: " + e.Message);
      return null;
    }
  }
  else
  {
    // The file doesn't have any content stored on Drive.
    return null;
  }

}

但是根据这个文件 “https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis/Apis/Authentication/IAuthenticator.cs?r=e6585033994bfb3a24d4c140db834cb14b9738b2” 它显示“不再支持 IAuthenticator”,因此上述代码不起作用。

我尝试使用 UserCredential,但它抛出“远程服务器返回错误:(401) 未授权。”。

所以请在 WPF 应用程序中提供相同的代码,或者我如何从 Google 驱动器下载任何类型的文件。

【问题讨论】:

    标签: c# google-drive-api


    【解决方案1】:

    根据文档,您需要下载新的 Google.Apis.Auth nuget 包。之后按照以下步骤操作

    • 访问 Google API 控制台
    • 如果这是您第一次,请点击“创建项目...”
    • 否则,请点击左上角“Google APIs”徽标下方的下拉菜单,然后点击“其他项目”下的“创建...”
    • 点击“API 访问”,然后点击“创建 OAuth 2.0 客户端 ID...”。
    • 输入产品名称并点击“下一步”。
    • 选择“已安装的应用程序”并单击“创建客户端 ID”。
    • 在新创建的“已安装应用程序的客户端 ID”中,将客户端 ID 和客户端机密复制到 AdSenseSample.cs 文件中。
    • 为您的项目激活 Drive API。

    参考Google APIs Client Library for .NET

    完成这些步骤后,您可以使用以下代码下载文件

    private async Task Run()
        {
            GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
            UserCredential credential;
            using (var stream = new System.IO.FileStream("client_secrets.json",
                System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None);
            }
    
            // Create the service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Drive API Sample",
            });
    
            await UploadFileAsync(service);
    
            // uploaded succeeded
            Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title);
            await DownloadFile(service, uploadedFile.DownloadUrl);
            await DeleteFile(service, uploadedFile);
        }
    
    
        private async Task DownloadFile(DriveService service, string url)
        {
            var downloader = new MediaDownloader(service);
            downloader.ChunkSize = DownloadChunkSize;
            // add a delegate for the progress changed event for writing to console on changes
            downloader.ProgressChanged += Download_ProgressChanged;
    
            // figure out the right file type base on UploadFileName extension
            var lastDot = UploadFileName.LastIndexOf('.');
            var fileName = DownloadDirectoryName + @"\Download" +
                (lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : "");
            using (var fileStream = new System.IO.FileStream(fileName,
                System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                var progress = await downloader.DownloadAsync(url, fileStream);
                if (progress.Status == DownloadStatus.Completed)
                {
                    Console.WriteLine(fileName + " was downloaded successfully");
                }
                else
                {
                    Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",
                        fileName, progress.BytesDownloaded);
                }
            }
        }
    

    您可以下载sample application 用于 google drive api。

    【讨论】:

    • 您能否帮我计算一下 ProgressChanged 事件中进度条的值。我正在尝试这个: void Download_ProgressChanged(IDownloadProgress obj) { prgrsVal = obj.BytesDownloaded;这里 prgrsVal 是我的属性绑定到 devexpress 的 ProgressBarEdit 控件的“值”属性。为此,我想要一些介于 0-100 之间的适当百分比值。 obj 没有要下载的文件的总字节数,如果有,我可以很容易地计算出来。所以请帮助我。
    • @user3771143 你可以这样做; var percentage = (prgrsVal / file.size) * 100; 这给你一个 0-100 之间的值
    猜你喜欢
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多