Let's implement a console application for uploading file to 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 uploading a file from local to Google cloud storage.
Code under Program.cs
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Storage.v1;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using GCSFileObject = Google.Apis.Storage.v1.Data.Object;
using System.IO;
internal class Program
{
long CurrentFileSizeInByte = 0;
// 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().UploadFile(@"C:\Temp\sample.pdf",
@"TestFolder/gcs-sample.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();
}
/// <summary>
/// Description: Upload file to GCS, as per passed arguments.
/// </summary>
/// <param name="localFileFullPathToUpload">
/// Full file path in local machine</param>
/// <param name="uploadedFilePathGcs">File name in GCS,
/// if we want sub-directories then separate it with "/" </param>
/// <returns></returns>
private async Task UploadFile(string localFileFullPathToUpload,
string uploadedFilePathGcs)
{
// File should exist first!
if (!string.IsNullOrWhiteSpace(localFileFullPathToUpload) &&
File.Exists(localFileFullPathToUpload))
{
// 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
}
);
// If different file, then get the correct MIME type here!
var fileMimeType = "application/pdf";
var fileStream = new FileStream(localFileFullPathToUpload,
FileMode.Open, FileAccess.Read);
var fileObj = new GCSFileObject
{
Name = uploadedFilePathGcs,
Updated = DateTime.Now,
Size = (ulong)fileStream.Length
};
CurrentFileSizeInByte = fileStream.Length;
// go for upload now!
var mediaUpload
= new ObjectsResource.InsertMediaUpload(service,
fileObj, GCSBucketName, fileStream,
fileMimeType);
mediaUpload.ProgressChanged += UploadProgress;
// Note: Google cloud storage API support
// chunk size multiple of 256KB. I kept minimum.
mediaUpload.ChunkSize = (256 * 1024);
await mediaUpload.UploadAsync(CancellationToken.None);
service.Dispose();
}
else
{
Console.WriteLine("Provided file name does not exist in local machine.");
}
}
private void UploadProgress(IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Starting:
Console.WriteLine("Upload starting, file size: " +
CurrentFileSizeInByte + " Bytes!");
break;
case UploadStatus.Completed:
Console.WriteLine("Upload completed!");
break;
case UploadStatus.Uploading:
Console.WriteLine("Uploaded "
+ progress.BytesSent + " Bytes.");
break;
case UploadStatus.Failed:
Console.WriteLine("Upload 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
6 Comments
6 - 1 =
** To prevent abusing comments from publishing, posted comments will be reviewed and then published!
By Krishna Rana,
about 9 years ago
i m not able to create bucket in google cloud, it ask for payment detail, is there any bucket available for free as demo bucket,
is your bucket "MySampleBucket" is paid or demo?
is your bucket "MySampleBucket" is paid or demo?
By Mritunjay Kumar,
about 9 years ago
Yes, i have implemented in ASP.Net. There you will need to first upload to your server and then from there, you can push the file to Google Cloud Storage. And yes you may update, rename or delete a file. Check here:
http://www.checkoutall.com/CodeSnippet/Category/C-Sharp/201501220542082288/google-cloud-storage-API-rename-a-file-includes-copy-file-and-delete-file
Note: the code snippet i have provided is for Google Cloud storage, not for Google Drive.
To implement this in ASP.Net, you will need to install latest Google API nuget package, which will add reference to all required dlls. And upload code will be more or less similar as mentioned in this code snippet.
http://www.checkoutall.com/CodeSnippet/Category/C-Sharp/201501220542082288/google-cloud-storage-API-rename-a-file-includes-copy-file-and-delete-file
Note: the code snippet i have provided is for Google Cloud storage, not for Google Drive.
To implement this in ASP.Net, you will need to install latest Google API nuget package, which will add reference to all required dlls. And upload code will be more or less similar as mentioned in this code snippet.
By Krishna Rana,
about 9 years ago
can u implement it, in asp.net,
let we have a fileupload to select a file, textbox to give title and a button control, on click of button file should be uploaded on google drive, later we can delete, update and rename it...
thanks
let we have a fileupload to select a file, textbox to give title and a button control, on click of button file should be uploaded on google drive, later we can delete, update and rename it...
thanks
By Mritunjay Kumar,
about 9 years ago
new Program().UploadFile(@"C:\Temp\sample.pdf", @"TestFolder/gcs-sample.pdf").Wait();
In above line, UploadFile takes 2 arguments, local file path and google cloud storage file, where file path will be uploaded. Wait() will not let below lines get executed, until UploadFile returns.
In above line, UploadFile takes 2 arguments, local file path and google cloud storage file, where file path will be uploaded. Wait() will not let below lines get executed, until UploadFile returns.
By Krishna Rana,
about 9 years ago
new Program().UploadFile(@"C:\Temp\sample.pdf",
@"TestFolder/gcs-sample.pdf").Wait();
what is (@"TestFolder/gcs-sample.pdf").Wait();) mean ?
@"TestFolder/gcs-sample.pdf").Wait();
what is (@"TestFolder/gcs-sample.pdf").Wait();) mean ?
Mritunjay Kumar
Works at
Mindfire Solutions
I mostly work with C#, ASP.NET, MVC, WCF, Web API, Entity FrameWork, MS Sql.
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 9 years ago
2576 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 9 years ago
2167 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 9 years ago
2827 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 9 years ago
2555 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 9 years ago
2988 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 9 years ago
2821 Views
Published by Mritunjay Kumar
, Mindfire Solutions,
about 9 years ago
4
if (4 > 1) {
Comments
} else {
Comment
}
8864 Views
All under this category...
No, that MySampleBucket is just a name which i used here. I don't have this setup in Google cloud storage. I have other account which have bucket setup. But, that's provided and used by our client. So, can not be shared.
And yes you will need to provide your details, including payment details to setup a bucket in Google cloud storage. As per Google https://console.developers.google.com/freetrial:
"
Why do you need my billing information?
We use your billing information to verify that you're a real person. Don't worry, you will not be billed for the free trial.
"