使用google-drive-api和c#将文件上传到驱动器

时间:2017-08-28 13:49:21

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

我正在运行此代码:

    private static string[] Scopes = { DriveService.Scope.DriveReadonly };
    private static string ApplicationName = "Drive API .NET Quickstart";
    private static string _folderId = "0B3s20ZXnD-M7dkdhZzZaeXZRTWc";
    private static string _fileName = "testFile";
    private static string _filePath = @"C:\Users\Yosi\Desktop\bla bla.rar";
    private static string _contentType = "application/zip";

    static void Main(string[] args)
    {
        Console.WriteLine("create cred");
        UserCredential credential = GetUserCredential();

        Console.WriteLine("Get Services");
        DriveService service = GetDriveService(credential);

        Console.WriteLine("Upload File");
        UploadFileToDrive(service, _fileName, _filePath, _contentType);

    }


    private static UserCredential GetUserCredential()
    {
        using (var stream = new FileStream("client_secret.json", FileMode.OpenOrCreate, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

            return GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user1",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }
    }

    private static DriveService GetDriveService(UserCredential credential)
    {
        return new DriveService(
            new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });
    }

    private static string UploadFileToDrive (DriveService service, string fileName, string filePath, string conentType)
    {
        var fileMatadata = new Google.Apis.Drive.v3.Data.File();
        fileMatadata.Name = fileName;
        fileMatadata.Parents = new List<string> { _folderId };

        FilesResource.CreateMediaUpload request;

        using (var stream = new FileStream(filePath, FileMode.Open))
        {
            request = service.Files.Create(fileMatadata, stream, conentType);
            request.Upload();
        }

        var file = request.ResponseBody;

        return file.Id;


    }
}

并获得以下异常:

enter image description here

当我调用该函数时:GetUserCredential();

任何可能导致错误的想法?

我实际上是逐字复制视频中的代码,但我看不出该错误的任何逻辑原因。我使用的视频:https://www.youtube.com/watch?v=nhQPwrrJ9kI&t=259s

2 个答案:

答案 0 :(得分:2)

这是失败的:

GoogleClientSecrets.Load(stream).Secrets

如果您没有,请使用以下说明生成文件:https://github.com/jay0lee/GAM/wiki/CreatingClientSecretsFile

确保文件client_secret.json存在于您的应用程序文件夹(exe所在的位置)中,然后:

using (var stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
            "client_secret.json"), FileMode.OpenOrCreate, FileAccess.Read))

当然,在部署应用程序时不要包含此文件,每个用户必须拥有并将自己的文件复制到应用程序文件夹。

答案 1 :(得分:1)

请仔细检查以下链接,了解如何获取用户凭据。

OAuth 2.0 - Credentials

这是代码示例:

   private async Task Run()
    {   
        UserCredential credential;
        using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { BooksService.Scope.Books },
                "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
        }

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

        var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync();
        ...
    }