为了从您的 C# 应用程序访问您的共享驱动器,您可以使用服务帐户。此功能的想法是拥有一个您可以通过编程方式登录并从中发出请求的帐户,而无需像使用“正常” OAuth2 流程那样明确允许该应用程序。您可以详细了解如何使用和创建服务帐户here。
使用服务帐户的示例 C# 代码:
using System;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Plus.v1;
using Google.Apis.Plus.v1.Data;
using Google.Apis.Services;
namespace Google.Apis.Samples.PlusServiceAccount
{
/// <summary>
/// This sample demonstrates the simplest use case for a Service Account service.
/// The certificate needs to be downloaded from the Google API Console
/// <see cref="https://console.developers.google.com/">
/// "Create another client ID..." -> "Service Account" -> Download the certificate,
/// rename it as "key.p12" and add it to the project. Don't forget to change the Build action
/// to "Content" and the Copy to Output Directory to "Copy if newer".
/// </summary>
public class Program
{
// A known public activity.
private static String ACTIVITY_ID = "z12gtjhq3qn2xxl2o224exwiqruvtda0i";
public static void Main(string[] args)
{
Console.WriteLine("Plus API - Service Account");
Console.WriteLine("==========================");
String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE";
var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { PlusService.Scope.PlusMe }
}.FromCertificate(certificate));
// Create the service.
var service = new PlusService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Plus API Sample",
});
Activity activity = service.Activities.Get(ACTIVITY_ID).Execute();
Console.WriteLine(" Activity: " + activity.Object.Content);
Console.WriteLine(" Video: " + activity.Object.Attachments[0].Url);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
在获取凭据并创建DriveService 实例后,您只需调用Files: create 端点,指定作为创建文件的父级(参见"Request body" 规范)共享驱动器的根或文件夹在共享云端硬盘中。
举个例子:
var fileMetadata = new File();
fileMetadata.Name = "My File";
fileMetadata.Parents = new List<string> { "YOUR_SHARED_DRIVE_FOLDER_ID" };
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("your_folder/your_file",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream);
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
参考
您可以在此处了解有关服务帐户的更多信息: