使用google drive api v3 C#上传文件或创建文件夹

时间:2017-10-01 18:59:18

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

我将Google Drive Api V3与C#集成在一起。我想执行多个操作,如上传文件,下载文件,创建文件夹,搜索文件,显示文件列表。使用Google云端硬盘的官方文档,我有以下代码。

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.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

    namespace GoogleDrive
{


class Program
{
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/drive-dotnet-quickstart.json
    static   string[] Scopes = { DriveService.Scope.Drive,
                       DriveService.Scope.DriveAppdata,
                       DriveService.Scope.DriveFile,
                       DriveService.Scope.DriveMetadataReadonly,
                       DriveService.Scope.DriveReadonly,
                       DriveService.Scope.DriveScripts};
    static string ApplicationName = "Drive API .NET Quickstart";

    static void Main(string[] args)
    {
        UserCredential credential;

        using (var stream =
            new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.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.
        var 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:");
        Console.WriteLine("Hello World");
        if (files != null && files.Count > 0)
        {
            foreach (var filee in files)
            {
                Console.WriteLine("{0} ({1})", filee.Name, filee.Id);
            }
        }
        else
        {
            Console.WriteLine("No files found.");
        }



        //file upload
         string path = "F:\\muneeb\\phone.jpg";
         var fileMetadata = new Google.Apis.Drive.v3.Data.File();
        // fileMetadata.Name = path.GetFileName(path);
        fileMetadata.MimeType = "image/jpeg";
        FilesResource.CreateMediaUpload request;
        using (var stream = new System.IO.FileStream(path, 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);        
        //end
        Console.Read();

    }   
}  

它显示了我的驱动器中的文件列表,但在上传文件时它返回空引用。获取request.Responsebody时文件保持空。

3 个答案:

答案 0 :(得分:0)

您可以参考此thread。确保您传递的是正确的范围。

string[] scopes = new string[] { DriveService.Scope.Drive,  
                           DriveService.Scope.DriveAppdata,
                           DriveService.Scope.DriveAppsReadonly,      
                           DriveService.Scope.DriveFile,   
                           DriveService.Scope.DriveMetadataReadonly, 
                           DriveService.Scope.DriveReadonly,      
                           DriveService.Scope.DriveScripts }; 

您也可以查看sample code in uploading a file

var fileMetadata = new File()
{
    Name = "photo.jpg"
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
                        System.IO.FileMode.Open))
{
    request = driveService.Files.Create(
        fileMetadata, stream, "image/jpeg");
    request.Fields = "id";
    request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);

答案 1 :(得分:0)

问题在于我使用的是Tutorial,而我的应用程序名称是&#34; ServUp&#34;当我创建应用程序时。 但是使用教程我没有在代码中更新我的应用程序名称。 教程代码是

 static string ApplicationName = "Drive API .NET Quickstart";

static void Main(string[] args)
{
    UserCredential credential;

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

在此之后,我发现了问题并更新了&#34; Drive API .NET快速入门&#34;到&#34; ServUp&#34;这解决了我的问题。

enter static string ApplicationName = "ServUp";

static void Main(string[] args)
{
    UserCredential credential;

    using (var stream =
        new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);
        credPath = Path.Combine(credPath, ".credentials/ServUp.json");code here

答案 2 :(得分:0)

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

示例代码:

var progress = request.Upload();

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