使用服务帐户创建驱动器服务Credential与Oauth2几乎相同。
var service = AuthenticationHelper.AuthenticateServiceAccount("[email protected]eaccount.com",@"C:\Users\HPUser\Downloads\e8bf61cc9963.p12");
/// <summary>
/// Authenticating to Google using a Service account
/// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
/// </summary>
/// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
/// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
/// <returns></returns>
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
{
// check the file exists
if (!File.Exists(keyFilePath))
{
Console.WriteLine("An Error occurred - Key file does not exist");
return null;
}
string[] scopes = new string[] { DriveService.Scope.Drive }; // View analytics data
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
try
{
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
上述方法将返回可用于进行其他调用的驱动器服务。这是我用来下载文件的方法。一旦你从files.list获得文件资源
var m = service.Files.List().Execute();
正如你可以看到它使用downloadURL来下载文件。
/// <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;
}
}
代码来自教程撕开Google Drive api C# download
谢谢您的帮助。让我进一步澄清我们的问题: – 2015-02-19 16:02:00
我们希望将文档上传到我们的存储帐户并让它给我们一个下载链接,然后我们希望将该链接放置在我们的网站上让用户下载该文件。我们希望的另一个选择是可能使用其中一个链接来允许我们网站的用户在iframe或其他东西中查看文件。所有这些链接在我们尝试时都会说“未经授权”,所以这仍然不是我们需要它工作的方式。你知道有什么办法让这个API呼叫以这种方式工作吗?再次感谢你的帮助。 – 2015-02-19 16:08:27
如果您希望得到的下载链接对于有链接的任何人都可用,则可能需要在上传文件时对文件设置适当的权限。 – 2016-12-07 14:12:18