📜 ⬆️ ⬇️

Downloading financial reports from Google Cloud Storage using the .NET API

Hi, Habr!
Not so long ago, at work, I was faced with the task of automating the receipt of financial reports from our Google account. In this publication, I would like to tell you how this is done using the example of the .NET API (C #) and warn you against errors that you encountered yourself.

So let's get started.

First, let's collect some primary information:


To summarize: we found a BucketID , downloaded a .p12 file , received an Email Address and sent an invite to it with the ability to read fin. reports.

Go ahead. Create a new console application project in Visual Studio. It is advisable to select a version of the .NET Framework of at least 4.5 (otherwise there will be problems with spaces in the file names).

After creating the project, install the nuget package with the API:

Install-Package Google.Apis.Storage.v1beta2 


The API version may change over time, so stay tuned.

But actually the whole code (assembled in pieces from different places). Replace the Bucket, email and path to the .p12 file with your own.

 using System; using System.IO; using System.Security.Cryptography.X509Certificates; using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using Google.Apis.Storage.v1beta2; namespace GoogleCloudStorageAPIClient { class Program { static void Main(string[] args) { const string bucket = "pubsite_prod_rev_XXXXXXXXXXXXXXXXXXXXX"; //  gs:// const string email = "YYYYYYYYYYYYYYYYYYYYYY@developer.gserviceaccount.com"; var certificate = new X509Certificate2( @"<   .p12 >", "notasecret", X509KeyStorageFlags.Exportable ); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(email) { Scopes = new[] { StorageService.Scope.DevstorageReadOnly } }.FromCertificate(certificate)); var service = new StorageService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "GoogleReportDownloader" }); var listRequest = service.Objects.List(bucket); var list = listRequest.Execute(); if (list != null) { Console.WriteLine("File count = {0}\r\n", list.Items.Count); foreach (var item in list.Items) { Console.WriteLine(item.Name); //   var getRequest = service.Objects.Get(bucket, item.Name); var objectName = string.Format("{0}\\{1}", @"C:\!temp\", item.Name); using (var fileStream = new FileStream(objectName, FileMode.Create, FileAccess.Write)) { getRequest.Download(fileStream); } } } } } } 


I hope someone this publication will save a lot of time and nerves.

Source: https://habr.com/ru/post/236149/


All Articles