使用服務帳戶創建驅動器服務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