【问题标题】:File upload or folder creation using google drive api v3 C#使用 google drive api v3 C# 上传文件或创建文件夹
【发布时间】:2017-10-01 18:59:17
【问题描述】:

我将 Google Drive Api V3 与 C# 集成。我想执行多种操作,例如上传文件、下载文件、创建文件夹、搜索文件、显示文件列表。使用谷歌驱动器的官方文档,我有以下代码。

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 时文件保持为 Null。

【问题讨论】:

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


    【解决方案1】:

    您可以参考这个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);
    

    【讨论】:

    • 示例代码对我不起作用(即使有所有额外的范围),并且 request.ResponseBody 始终为null。我在执行代码之前检查了图像是否存在,所以我的路径必须是正确的。请帮忙!
    【解决方案2】:

    问题是我在创建应用程序时使用的是教程,而我的应用程序名称是“ServUp”。 但是使用教程我没有在代码中更新我的应用程序名称。 教程代码是

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

    在此之后,我发现了问题并将应用程序名称从“Drive API .NET Quickstart”更新为“ServUp”,从而解决了我的问题。

    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
    

    【讨论】:

      【解决方案3】:

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

      示例代码:

      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
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 2017-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多