gpt4 book ai didi

c# - 使用 Google Drive API 下载文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:48 26 4
gpt4 key购买 nike

我已经使用 Google API 从 Google 驱动器下载文件,但不幸的是我遇到了一个问题,即访问路径“Daimto.GoogleDrive.Auth.Store”被拒绝。我不知道如何解决这个问题,也不知道我在 GoogleWebAuthorizationBroker.AuthorizeAsync() 方法中使用了正确的参数。

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Google.Apis.Drive.v2;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using Google.Apis.Drive.v2.Data;
using System.Collections.Generic;

namespace DownloadFromGoogleDrive
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Scopes for use with the Google Drive API
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential =
GoogleWebAuthorizationBroker
.AuthorizeAsync(new ClientSecrets
{
ClientId = "581284671387-uqf7v4ci6olktjthppd590uv8vnaqvc0.apps.googleusercontent.com"
,
ClientSecret = "eZZd5zTThgKroNClKDKWR-mJ"
}
, scopes
, Environment.UserName
, CancellationToken.None
, new FileDataStore("Daimto.GoogleDrive.Auth.Store")
).Result;

DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});


}

/// <summary>
/// Download a file
/// Documentation: https://developers.google.com/drive/v2/reference/files/get
/// </summary>
/// <param name="_service">a Valid authenticated DriveService</param>
/// <param name="_fileResource">File resource of the file to download</param>
/// <param name="_saveTo">location of where to save the file including the file name to save it as.</param>
/// <returns></returns>
public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
{

if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{
try
{
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl);
byte[] arrBytes = x.Result;
System.IO.File.WriteAllBytes(_saveTo, arrBytes);
return true;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return false;
}
}
else
{
// The file doesn't have any content stored on Drive.
return false;
}
}

}
}

最佳答案

FileDataStore 将您的身份验证信息存储在 %AppData% 目录中。

所以你最终得到的是这样的

C:\Users\linda_l\AppData\Roaming\Daimto.GoogleDrive.Auth.Store

您需要确保运行应用程序的进程可以访问 %AppData% 目录或创建您自己的 Idatastore 实现以将文件存储在其他地方,比如当前目录 LocalFileDataStore.cs

您可以在此处找到更详细地解释这一点的教程。 Google Oauth2 C#

关于c# - 使用 Google Drive API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27356741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com