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

如何让Google Drive API v3示例在C#中工作?,c#,google-api,google-drive-api,C#,Google Api,Google Drive Api,因此,我从GoogleDriveAPI.NETQuickStart(v3)中复制了代码,代码运行良好,如预期的那样列出了我的GoogleDrive上的所有文件。但是,当我尝试使用找到的上载示例代码时,我无法将本地存储的图像上载到驱动器,并且请求。ResponseBody返回null。我还添加了额外的驱动器作用域,但没有任何帮助。为什么上传文件的示例代码不起作用 我的代码如下: using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; u

因此,我从GoogleDriveAPI.NETQuickStart(v3)中复制了代码,代码运行良好,如预期的那样列出了我的GoogleDrive上的所有文件。但是,当我尝试使用找到的上载示例代码时,我无法将本地存储的图像上载到驱动器,并且
请求。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);
        }
使用Google.api.Auth.OAuth2;
使用Google.api.Drive.v3;
使用Google.api.Drive.v3.Data;
使用Google.api.Services;
使用Google.api.Util.Store;
使用制度;
使用System.Collections.Generic;
使用系统线程;
使用System.Windows;
名称空间Google\u Drive\u REST\u应用程序
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
静态字符串[]范围={DriveService.Scope.Drive,
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveMetadataReadonly,
DriveService.Scope.DriveReadonly,
DriveService.Scope.DriveScripts};
静态字符串ApplicationName=“谷歌硬盘REST应用程序”;
用户凭证;
驾驶服务;
公共主窗口()
{
初始化组件();
使用(var)流=
新的System.IO.FileStream(“credentials.json”,System.IO.FileMode.Open,System.IO.FileAccess.ReadWrite))
{
//文件token.json存储用户的访问和刷新令牌,并被创建
//首次完成授权流时自动执行。
字符串credPath=“token.json”;
凭证=GoogleWebAuthorizationBroker.AuthorizationAsync(
GoogleClientSecrets.Load(stream.Secrets),
范围,
“用户”,
取消令牌。无,
新文件数据存储(credPath,true))。结果;
Console.WriteLine(“凭证文件保存到:”+credPath);
}
//创建驱动器API服务。
service=new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=ApplicationName,
});
//定义请求的参数。
fileResource.ListRequest ListRequest=service.Files.List();
listRequest.PageSize=10;
listRequest.Fields=“nextPageToken,files(id,name)”;
//列出文件。
IList files=listRequest.Execute()
.档案;
Console.WriteLine(“文件:”);
if(files!=null&&files.Count>0)
{
foreach(文件中的var文件)
{
Console.WriteLine(“{0}({1})”,file.Name,file.Id);
}
}
其他的
{
WriteLine(“未找到任何文件”);
}
Console.Read();
}
私有void btnUpload\u单击(对象发送者,路由目标e)
{
var fileMetadata=new Google.api.Drive.v3.Data.File()
{
Name=“photo.jpg”
};

FileResource.CreateMediaUpload请求; 使用(var stream=new System.IO.FileStream(“E:/My Documents/Pictures/test_pic.jpg”, System.IO.FileMode.Open) { 请求=service.Files.Create( 文件元数据,流,“图像/jpeg”); request.Fields=“id”; request.Upload(); } var file=request.ResponseBody; Console.WriteLine(“文件ID:+File.ID”); }
我刚刚测试了以下代码,效果很好。希望它能帮助您

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

这是一个指向

的链接,其他与驱动器上载有问题的人应查看您上载的异常,这将使您更好地了解实际问题

示例代码:

var progress = request.Upload();

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

这就是我如何找到问题的根源。

请编辑你的问题并描述你正在解决的问题。我以为我已经描述了我面临的问题?!如果这是你的意思,我已经删除了不必要的最后一段?@DalmTo感谢你的帮助,顺便说一句……也许你可以“传播对谷歌API的热爱”通过提供一些实际的建议来解决我提出的问题?我很乐意帮助您定义无法上传。是否有错误?这在哪里运行?文件有多大?是什么类型的文件。很抱歉,您感到沮丧,但没有足够的信息来理解此问题。这也可能有助于我明天开始工作并且可以看看您对我的问题“filesource.CreateMediaUpload不包含“Execute”的定义”的回答。@DalmTo我最好切换到Google Drive API的v2,因为v3似乎没有工作示例?大多数文档和建议似乎也适用于v2。我猜
request.Execute()
例如,仅适用于v2?很好,我感觉很糟糕,所以我自己创建了一个测试版本。我能看到的唯一区别是您的\路径错误,可能它找不到文件。我的工作正常。好的,我修复了反斜杠,复制了您的Oauth2类。我现在可以成功上载。谢谢您的帮助。