要在C#中使用Google Drive API v3,您需要遵循以下步骤:
Google.Apis.Drive.v3
包。using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace GoogleDriveExample
{
class Program
{
// 如果修改这些范围,请删除token.json文件。
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Google Drive API .NET Quickstart";
static async Task Main(string[] args)
{
var credential = await GetUserCredentialAsync();
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// 示例:列出文件
await ListFilesAsync(service);
}
private static async Task<UserCredential> GetUserCredentialAsync()
{
using var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read);
string credPath = "token.json";
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true));
}
private static async Task ListFilesAsync(DriveService service)
{
var request = service.Files.List();
request.PageSize = 10;
request.Fields = "nextPageToken, files(id, name)";
var files = await request.ExecuteAsync();
if (files.Files == null || files.Files.Count == 0)
Console.WriteLine("No files found.");
else
{
Console.WriteLine("Files:");
foreach (var file in files.Files)
{
Console.WriteLine($"{file.Name} ({file.Id})");
}
}
}
}
}
领取专属 10元无门槛券
手把手带您无忧上云