使用服务帐户将文件上传到Google Merchant Center中生成的Google云端存储分区

时间:2014-11-12 00:11:33

标签: c# .net google-api google-cloud-storage google-authentication

我可以使用以下代码将文件上传到Google Cloud Storage存储桶。我手动创建了桶。

        String serviceAccountEmail = "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com";

        var certificate = new X509Certificate2(@"C:\...\projectname-xxxxxxxxxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
        var scopes = new[] { @"https://www.googleapis.com/auth/devstorage.full_control" };

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = scopes
            }.FromCertificate(certificate));

        StorageService service = new StorageService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Shipment Feed",
        });

        var bucketToUpload = "bucket-created-by-me";
        var newObject = new Google.Apis.Storage.v1.Data.Object()
        {
            Bucket = bucketToUpload,
            Name = "ShipmentFeed.txt"
        };


        FileStream fileStream = null;
        var path = @"C:\...\file.txt";
        fileStream = new FileStream(path, FileMode.Open);
        var uploadRequest = new ObjectsResource.InsertMediaUpload(service, newObject,
           bucketToUpload, fileStream, "text/plain");
        uploadRequest.Upload();

现在,当我尝试将文件上传到Google Merchant Center为同一个Google帐户生成的存储桶时,我遇到了问题。我使用上面的代码,只需将广告管理系统名称更改为Google Merchant中心通过“设置 - > Google云端存储”提供的值

var bucketToUpload = "merchantxxxxxxx";

此过程未将文件上传到存储桶(使用gsutil测试 - 存储桶存在于我的项目中但为空)。为什么我不能上传文件?

1 个答案:

答案 0 :(得分:1)

您的代码未授权访问Google云端存储。 创建ServiceAccountCredential后,您必须通过调用以下方式获取访问令牌:

 ServiceAccountCredential sac = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = scopes
            }.FromCertificate(certificate));
 var cts = new CancellationToken();
 var response = sac.RequestAccessTokenAsync(cts).Result;

如果响应为真,您的ServiceAccountCredential对象将设置 ServiceAccountCredential.Token.AccessToken

然后,当您创建uploadRequest时,您必须提供您获得的AccessToken:

var uploadRequest = new ObjectsResource.InsertMediaUpload(service, newObject,
       bucketToUpload, fileStream, "text/plain");

uploadRequest.OauthToken = sac.Token.AccessToken;

最后致电:

uploadRequest.Upload();