我已成功将文件上传到Google存储,例如:
Task upload = Task.Run(async () =>
{
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = "*****";
clientSecrets.ClientSecret = "*****";
var scopes = new[] { @"https://www.googleapis.com/auth/devstorage.full_control" };
var cts = new CancellationTokenSource();
var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, "mail@example.com ", cts.Token);
await userCredential.RefreshTokenAsync(cts.Token);
var service = new StorageService();
var bucketsQuery = service.Buckets.List("MyProjectName");
bucketsQuery.OauthToken = userCredential.Token.AccessToken;
var buckets = bucketsQuery.Execute();
Bucket bucketToUpload = buckets.Items.FirstOrDefault();
var newFile = new Google.Apis.Storage.v1.Data.Object()
{
Bucket = bucketToUpload.Name,
Name = TargetFileName
};
FileStream fileStream = null;
try
{
fileStream = new FileStream(TargetFilePath, FileMode.Open);
var uploadRequest = new ObjectsResource.InsertMediaUpload(service, newFile, bucketToUpload.Name, fileStream, "audio/wav");
uploadRequest.OauthToken = userCredential.Token.AccessToken;
await uploadRequest.UploadAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (fileStream != null) fileStream.Dispose();
}
});
await upload;
我也想做的是从存储桶中删除所有内容。搜索互联网时,我似乎找不到可行的方法。有人可以给我提供代码示例吗?
非常感谢!
答案 0 :(得分:1)
我建议使用C# client libraries。有了这些,可以通过使用以下代码来删除存储桶中的文件:
using System;
using Google.Cloud.Storage.V1;
namespace csharp {
public class deletingFilesFromBucket
{
static void Main(string[] args)
{
var storage = StorageClient.Create();
var bucketName = "MyBucket"
foreach (var storageObject in storage.ListObjects(bucketName, ""))
{
storage.DeleteObject(bucketName, storageObject.Name);
Console.WriteLine($"Deleted {storageObject.Name}.");
}
}
}
}
您可以在this document中找到对此的参考。