如何在WPF中安装Google驱动器中的文件 - 已安装的应用程序

时间:2014-06-24 12:40:38

标签: c# google-drive-api

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

中Google文档中的代码
 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驱动器下载任何类型的文件。

1 个答案:

答案 0 :(得分:2)

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

  • 访问Google API控制台
  • 如果这是您第一次,请点击“创建项目...”
  • 否则,请点击左上方“Google API”徽标下方的下拉列表,然后点击“其他项目”下的“创建...”
  • 点击“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);
            }
        }
    }

您可以为google drive apis下载sample application