如何使Google Drive API v3示例在C#中工作?

时间:2019-04-02 09:20:33

标签: c# google-api google-drive-api

因此,我已从Google Drive API .NET快速入门(v3)here复制了代码,该代码运行正常,按预期方式列出了Google Drive上的所有文件。但是,当我尝试使用发现的here上传示例代码时,无法将本地存储的图像上传到我的云端硬盘,并且request.ResponseBody返回null。我还添加了其他云端硬盘范围,但没有帮助。为什么上传文件的示例代码不起作用?

我的代码如下:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;

namespace Google_Drive_REST_App
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static string[] Scopes = { DriveService.Scope.Drive,
                       DriveService.Scope.DriveAppdata,
                       DriveService.Scope.DriveFile,
                       DriveService.Scope.DriveMetadataReadonly,
                       DriveService.Scope.DriveReadonly,
                       DriveService.Scope.DriveScripts};
        static string ApplicationName = "Google Drive REST App";

        UserCredential credential;
        DriveService service;

        public MainWindow()
        {
            InitializeComponent();

            using (var stream =
                new System.IO.FileStream("credentials.json", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine("{0} ({1})", file.Name, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();

        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = "photo.jpg"
            };
            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream("E:/My Documents/Pictures/test_pic.jpg",
                                    System.IO.FileMode.Open))
            {
                request = service.Files.Create(
                    fileMetadata, stream, "image/jpeg");
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;
            Console.WriteLine("File ID: " + file.Id);
        }

2 个答案:

答案 0 :(得分:1)

我刚刚测试了以下代码,它工作正常。希望对您有帮助。

 <input foo [id]="i" />

这是指向Oauth2Example

的链接

答案 1 :(得分:0)

其他人在云端硬盘上传中遇到问题的人应该从您上传的内容中查看“异常”,这样可以使您更好地了解实际问题。

示例代码:

var progress = request.Upload();

if (progress.Exception != null)
{
   //Log execption, or break here to debug
   YourLoggingProvider.Log(progress.Exception.Message.ToString());
}

这就是解决问题的方法。