【问题标题】:How to get the Google Drive API v3 Samples to work in C#?如何让 Google Drive API v3 示例在 C# 中工作?
【发布时间】:2019-04-02 09:20:33
【问题描述】:

所以我从 Google Drive API .NET Quickstart (v3) here 复制了代码,并且代码运行良好,按预期列出了我的 Google Drive 上的所有文件。但是,当我尝试使用here 找到的上传示例代码时,我无法将本地存储的图像上传到我的驱动器,request.ResponseBody 返回null。我还添加了额外的 Drive 范围,但它没有帮助。为什么上传文件的示例代码不起作用?

我的代码如下:

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);
        }

【问题讨论】:

  • 请编辑您的问题并描述您遇到的问题。
  • 我以为我已经描述了我遇到的问题?!如果这就是你的意思,我已经删除了不必要的最后一段?
  • @DalmTo 感谢您的帮助顺便说一句...也许您可以通过提供一些实际建议来解决我提出的问题来“传播对 Google API 的热爱”?
  • 如果您定义无法上传,我很乐意为您提供帮助。有错误吗?这是在哪里运行?文件有多大?它是什么类型的文件。很抱歉您感到沮丧,但没有足够的信息来理解这个问题。
  • 这可能也会有所帮助,直到我明天上班,可以看看你对我的问题的回复developers.google.com/api-client-library/dotnet/guide/…

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


【解决方案1】:

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

class Program
    {
        static void Main(string[] args)
        {

            var service = Oauth2Example.GetDriveService(@"C:\Users\linda\Documents\.credentials\NativeClient.json", "test",
                new[] {Google.Apis.Drive.v3.DriveService.Scope.Drive});

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = "flag.jpg"
            };

            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(@"C:\temp\flag.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);
            Console.ReadKey();
        }
    }

这是Oauth2Example的链接

【讨论】:

  • “FilesResource.CreateMediaUpload 不包含‘执行’的定义”。
  • @DalmTo 我最好切换到 Google Drive API 的 v2,因为似乎没有适用于 v3 的示例?大多数文档和建议似乎也适用于 v2。我猜request.Execute() 例如仅适用于 v2?
  • 很好,我感觉很糟糕,所以我自己创建了一个测试版本,我能看到的唯一区别是你的 \ 在你的路径中是错误的,也许它找不到文件。我的作品。
  • 好的,我修正了反斜杠并复制了你的 Oauth2 类。我现在可以成功上传了。感谢您的帮助。
【解决方案2】:

其他对云端硬盘上传有问题的人应查看您上传的异常,这将使您更好地了解实际问题。

示例代码:

var progress = request.Upload();

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

这就是我解决问题的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多