Let's implement a console application for downloading file from Google cloud storage with help of Google.Apis.Storage.v1.
My dev machine: .Net 4.5, Visual Studio 2012
Prerequisites: Install Google.Apis.Storage.v1 from NuGet packages.
File details:
Program.cs: Entry point of the application, contains Main function. This file will also contain different other functions required for downloading a file from Google cloud storage.
Code under Program.cs
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Download;
using Google.Apis.Storage.v1;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using GCSFileObject = Google.Apis.Storage.v1.Data.Object;
using System.IO;
internal class Program
{
public long CurrentFileSizeInByte = 0;
public string LocalDownloadPath = @"C:\Temp";
// Below details can be retrieved from Google console site.
const string GCSBucketName = "MySampleBucket";
const string P12KeyFullPath = @"C:\Temp\key.p12";
const string P12KeySecret = "gcssecret";
const string GCSServiceAccountEmail
= "GetItFromGoogleCloudStorageConsole@developer.gserviceaccount.com";
const string GCSApplicationName = "MySampleProject";
private static void Main(string[] args)
{
try
{
new Program().DownloadFile("Test.pdf").Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("ERROR: " + e.Message);
}
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private async Task DownloadFile(string filePathInGcs)
{
// Loading the Key file
var certificate
= new X509Certificate2(P12KeyFullPath, P12KeySecret,
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet |
X509KeyStorageFlags.Exportable);
// Authentication first!
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(GCSServiceAccountEmail)
{
Scopes = new[] { StorageService.Scope.DevstorageReadWrite }
}.FromCertificate(certificate));
// Well, all setup now!
// Let's move to initializing service for Google API!
var service = new StorageService(
new BaseClientService.Initializer
{
ApplicationName = GCSApplicationName,
HttpClientInitializer = credential
}
);
// First get file meta data from GCS, which
// will contain media link of GCS
var fileRequest =
new ObjectsResource.GetRequest(service,
GCSBucketName, filePathInGcs);
var fileMetaDataObj = fileRequest.Execute();
// Let's download the file now!
fileRequest.MediaDownloader.ProgressChanged += DownloadProgress;
// Note: Google cloud storage API support
// chunk size multiple of 256KB. I kept minimum.
fileRequest.MediaDownloader.ChunkSize = (256 * 1024);
if (fileMetaDataObj.Size.HasValue)
{
Console.WriteLine(DateTime.Now
+ ": Downloading file of size "
+ fileMetaDataObj.Size.Value + " Bytes.");
}
var downloadStream =
new FileStream(Path.Combine(LocalDownloadPath, filePathInGcs),
FileMode.Create,
FileAccess.Write);
await fileRequest.MediaDownloader.DownloadAsync(fileMetaDataObj.MediaLink,
downloadStream,
CancellationToken.None);
service.Dispose();
}
private void DownloadProgress(IDownloadProgress progress)
{
switch (progress.Status)
{
case DownloadStatus.Completed:
Console.WriteLine("Download completed!");
break;
case DownloadStatus.Downloading:
Console.WriteLine("Downloaded " +
progress.BytesDownloaded + " Bytes.");
break;
case DownloadStatus.Failed:
Console.WriteLine("Download failed "
+ Environment.NewLine
+ progress.Exception.Message
+ Environment.NewLine
+ progress.Exception.StackTrace
+ Environment.NewLine
+ progress.Exception.Source
+ Environment.NewLine
+ progress.Exception.InnerException
+ Environment.NewLine
+ "HR-Result" + progress.Exception.HResult);
break;
}
}
}
Discussion
4 Comments
25 - Five
** To prevent abusing comments from publishing, posted comments will be reviewed and then published!
By Raj,
about 4 years ago
Hi Kumar,
really thanks a lot, i can download file, but have to try so many time some time request can not get through, some time task revoked. don't know why it happens. but i repeatedly tried and worked.
I need futher help for my app there are following folders in buckets,
Buckets/MyBucketname/stats/installs
Buckets/MyBucketname/stats/ratings
Buckets/MyBucketname/stats/crashes
I want to download in one shot for all the filesaccording to folder name. how i can do this and when i see it is year wise on developer console but if i clicked on bucket i can not identify this file is for 2015 or 2016 year. how to download year and month wise. please revert soon will be very thankfull
really thanks a lot, i can download file, but have to try so many time some time request can not get through, some time task revoked. don't know why it happens. but i repeatedly tried and worked.
I need futher help for my app there are following folders in buckets,
Buckets/MyBucketname/stats/installs
Buckets/MyBucketname/stats/ratings
Buckets/MyBucketname/stats/crashes
I want to download in one shot for all the filesaccording to folder name. how i can do this and when i see it is year wise on developer console but if i clicked on bucket i can not identify this file is for 2015 or 2016 year. how to download year and month wise. please revert soon will be very thankfull
By Mritunjay Kumar,
about 4 years ago
Hi Raj,
P12 key file will be generated through google cloud storage site. Check this link:
https://cloud.google.com/storage/docs/authentication#generating-a-private-key
When you will select P12 in the wizard, it will provide you the key file, with extension p12. Save that key file in your application folder and then get full path of that key file and assign that path to P12KeyFullPath.
const string P12KeyFullPath = @"C:\Temp\key.p12";
In that process you will also get a password, which will be private key's password; This will be used in const string P12KeySecret = "gcssecret";
I hope this helps.
P12 key file will be generated through google cloud storage site. Check this link:
https://cloud.google.com/storage/docs/authentication#generating-a-private-key
When you will select P12 in the wizard, it will provide you the key file, with extension p12. Save that key file in your application folder and then get full path of that key file and assign that path to P12KeyFullPath.
const string P12KeyFullPath = @"C:\Temp\key.p12";
In that process you will also get a password, which will be private key's password; This will be used in const string P12KeySecret = "gcssecret";
I hope this helps.
By Raj,
about 4 years ago
Hi,
I wan to download file from my bucket, i used your sample but what is P12KeyFullPath, i guess it is json file created when you create service account. if i am wrong please correct me.
what is P12KeySecret totally unaware from this. my code is not working.
Its urgent please reply soon
I wan to download file from my bucket, i used your sample but what is P12KeyFullPath, i guess it is json file created when you create service account. if i am wrong please correct me.
what is P12KeySecret totally unaware from this. my code is not working.
Its urgent please reply soon
Mritunjay Kumar

I mostly work with C#, ASP.NET, MVC, WCF, Web API, Entity FrameWork, MS Sql.
More under this category...
Published by Mritunjay Kumar
, Mindfire Solutions,
about 5 years ago
1784 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 5 years ago
1596 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 5 years ago
2241 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 5 years ago
1932 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 6 years ago
2298 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 6 years ago
2097 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 6 years ago
6
if (6 > 1) {
Comments
} else {
Comment
}
6941 Views
All under this category...
I did not try downloading multiple files together or all files from a folder in one request, as that was not needed in my project. So, not sure. And I could not find it easily. You may dig Google API library Google.Apis.Storage.V1 more and see if you could find some thing helpful for this requirement.
With gsutil tool you can do that. But, I did not use that; So, can't help there.
https://cloud.google.com/storage/docs/gsutil