在c#4.5中使用Google驱动器 [英] Use Google drive in c#4.5

查看:163
本文介绍了在c#4.5中使用Google驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想在c#应用程序中使用Google驱动API上传和下载文件。



我正在使用以下代码。

Hi,

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

I am using following code.

/*
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

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.+

推荐答案

您好,我使用/制作此代码上传,工作正常但它在VB中,我很遗憾知道C#,但你可以使用翻译器将代码转换为c#。





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#.


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





甚至可以设置mime类型。

如果它可以帮助你(或任何人) )请帮助我使用任何工作代码来使用Google日历或联系人或任务或Gmail的功能。

VB中没有太多信息可以与Google Apis一起使用。

祝你好运。

Alan Alvarez



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


这篇关于在c#4.5中使用Google驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆