Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to upload and download file using Google drive API in c# Application.

I am using following code.
C#
/*
Copyright 2013 Google Inc

Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Threading;
using System.Threading.Tasks;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Download;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Logging;
using Google.Apis.Services;
using Google.Apis.Upload;

namespace Drive.Sample
{
/// <summary>
/// A sample for the Drive API. This samples demonstrates resumable media upload and media download.
/// See https://developers.google.com/drive/ for more details regarding the Drive API.
/// </summary>
///

class Program
{
static Program()
{
// initialize the log instance
// ApplicationContext.RegisterLogger(new log4net());
log4net.Config.XmlConfigurator.Configure();
Logger = ApplicationContext.Logger.ForType<resumableupload><program>>();
}

#region Consts

private const int KB = 0x400;
private const int DownloadChunkSize = 256 * KB;

// CHANGE THIS with full path to the file you want to upload
//private const string UploadFileName = @"FILE_TO_UPLOAD";
private const string UploadFileName = @"Drill Shirt";

// CHANGE THIS with a download directory
//private const string DownloadDirectoryName = @"DIRECTORY_FOR_DOWNLOADING";
private const string DownloadDirectoryName = @"C:\Users\ankit\Desktop\GD_Download";

// CHANGE THIS if you upload a file type other than a jpg
private const string ContentType = @"image/jpeg";

#endregion

/// <summary>The logger instance.</summary>
private static readonly ILogger Logger;

/// <summary>The Drive API scopes.</summary>
private static readonly string[] Scopes = new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive };

/// <summary>
/// The file which was uploaded. We will use its download Url to download it using our media downloader object.
/// </summary>
private static File uploadedFile;

static void Main(string[] args)
{
Console.WriteLine("Google Drive API Sample");

try
{

new Program().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("ERROR: " + e.Message);
}
}

Console.WriteLine("Press any key to continue...");
//Console.ReadKey();
Console.Read();
}

private async Task Run()
{ 
GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "685479681237-fh04tlvll9gach7841vdl5gk988qa17u.apps.googleusercontent.com",
ClientSecret = "zjpOCLKGxVWgETZgNwZRaed-"
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;

//UserCredential credential;
//using (var stream = new System.IO.FileStream("client_secrets.json",
// System.IO.FileMode.Open, System.IO.FileAccess.Read))
//{
// credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
// GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None);
//}

// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive.Sample",
});

await UploadFileAsync(service);

// uploaded succeeded
Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title);
await DownloadFile(service, uploadedFile.DownloadUrl);
await DeleteFile(service, uploadedFile);
}

/// <summary>Uploads file asynchronously.</summary>
private Task<iuploadprogress> UploadFileAsync(DriveService service)
{
var title = UploadFileName;
if (title.LastIndexOf('\\') != -1)
{
title = title.Substring(title.LastIndexOf('\\') + 1);
}

var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open,
System.IO.FileAccess.Read);

var insert = service.Files.Insert(new File { Title = title }, uploadStream, ContentType);

insert.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2;
insert.ProgressChanged += Upload_ProgressChanged;
insert.ResponseReceived += Upload_ResponseReceived;

var task = insert.UploadAsync();

task.ContinueWith(t =>
{
// NotOnRanToCompletion - this code will be called if the upload fails
Console.WriteLine("Upload Filed. " + t.Exception);
}, TaskContinuationOptions.NotOnRanToCompletion);
task.ContinueWith(t =>
{
Logger.Debug("Closing the stream");
uploadStream.Dispose();
Logger.Debug("The stream was closed");
});

return task;
}

/// <summary>Downloads the media from the given URL.</summary>
private async Task DownloadFile(DriveService service, string url)
{
var downloader = new MediaDownloader(service);
downloader.ChunkSize = DownloadChunkSize;
// add a delegate for the progress changed event for writing to console on changes
downloader.ProgressChanged += Download_ProgressChanged;

// figure out the right file type base on UploadFileName extension
var lastDot = UploadFileName.LastIndexOf('.');
var fileName = DownloadDirectoryName + @"\Download" +
(lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : "");
using (var fileStream = new System.IO.FileStream(fileName,
System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
var progress = await downloader.DownloadAsync(url, fileStream);
if (progress.Status == DownloadStatus.Completed)
{
Console.WriteLine(fileName + " was downloaded successfully");
}
else
{
Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",
fileName, progress.BytesDownloaded);
}
}
}

/// <summary>Deletes the given file from drive (not the file system).</summary>
private async Task DeleteFile(DriveService service, File file)
{
Console.WriteLine("Deleting file '{0}'...", file.Id);

await service.Files.Delete(file.Id).ExecuteAsync();
Console.WriteLine("File was deleted successfully");

}

#region Progress and Response changes

static void Download_ProgressChanged(IDownloadProgress progress)
{
Console.WriteLine(progress.Status + " " + progress.BytesDownloaded);
}

static void Upload_ProgressChanged(IUploadProgress progress)
{
Console.WriteLine(progress.Status + " " + progress.BytesSent);
}

static void Upload_ResponseReceived(File file)
{
uploadedFile = file;
}

#endregion
}

}


But when its going in below line

C#
new ClientSecrets
{
ClientId = "xxxxxxxxxxxl9gach7841vdl5gk988qa17u.apps.googleusercontent.com",
ClientSecret = "aaaaaaawZRaed-"
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;

After that i am not getting any output or any error.



Please help me.

Thanks in advance.+
Posted
Updated 2-Sep-14 13:30pm
v2
Comments
[no name] 2-Sep-14 19:33pm    
It's google's code, why are you not asking them about it? The URL is right there in the code....

1 solution

Hi, I use/made this code to Upload, works fine but its in VB, sadly I dont know C# but you can use a translator to convert the code to c#.


VB
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OpenFileDialog1.InitialDirectory = "THE DIRECTORY PATH"
        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim Secrets = New ClientSecrets()
            Secrets.ClientId = "CLIENT ID HERE"
            Secrets.ClientSecret = "CLIENT SECRET HERE"

            Dim scope = New List(Of String)
            scope.Add(DriveService.Scope.Drive)

            Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scope, "USER", CancellationToken.None).Result()

            Dim initializer = New BaseClientService.Initializer
            initializer.HttpClientInitializer = credential
            initializer.ApplicationName = "APPLICATION NAME"

            Dim service = New DriveService(initializer)

            Dim body = New File
            body.Title = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
            body.Description = "DESCRIPTION"
            Select Case System.IO.Path.GetExtension(OpenFileDialog1.FileName)
                Case ".avi"
                    body.MimeType = "video/x-msvideo"
                Case ".css"
                    body.MimeType = "text/css"
                Case ".doc"
                    body.MimeType = "application/msword"
                Case ".htm", ".html"
                    body.MimeType = "text/html"
                Case ".bmp"
                    body.MimeType = "image/bmp"
                Case ".gif"
                    body.MimeType = "image/gif"
                Case ".jpeg"
                    body.MimeType = "image/jpeg"
                Case ".jpg"
                    body.MimeType = "image/jpeg"
                Case ".docx"
                    body.MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                Case ".pdf"
                    body.MimeType = "application/pdf"
                Case ".ppt"
                    body.MimeType = "application/vnd.ms-powerpoint"
                Case ".pptx"
                    body.MimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
                Case ".xls"
                    body.MimeType = "application/vnd.ms-excel"
                Case ".xlsx"
                    body.MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                Case ".txt"
                    body.MimeType = "text/plain"
                Case ".zip"
                    body.MimeType = "application/zip"
                Case ".rar"
                    body.MimeType = "application/x-rar-compressed"
                Case ".mp3"
                    body.MimeType = "audio/mpeg"
                Case ".mp4"
                    body.MimeType = "video/mp4"
                Case ".png"
                    body.MimeType = "image/png"
                Case Else
                    body.MimeType = "application/octet-stream"
            End Select

            Dim byteArray = System.IO.File.ReadAllBytes(OpenFileDialog1.FileName)
            Dim stream = New System.IO.MemoryStream(byteArray)

            Dim request = service.Files.Insert(body, stream, body.MimeType)
            request.Upload()

            body = request.ResponseBody
            MessageBox.Show("The File id is: " & body.Id, "Subido")
        End If
    End Sub


Even works to set the mime type.
If it helps you (or anyone) please help me with any working code to use functions of Google Calendar or Contacts or Tasks or Gmail.
There is no much information in VB to work with Google Apis.
Good luck.
Alan Alvarez
 
Share this answer
 
v2
Comments
Member 15250281 25-Jul-21 17:27pm    
thanks very much
try to upload file with 20mg size and tell me result

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900