代码之家  ›  专栏  ›  技术社区  ›  Muneeb Akhtar

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

  •  0
  • Muneeb Akhtar  · 技术社区  · 7 年前

    我将Google Drive Api V3与C集成。我想执行多种操作,如上传文件,下载文件,创建文件夹,搜索文件,显示文件列表。使用Google 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.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();
    
        }   
    }  
    

    3 回复  |  直到 7 年前
        1
  •  0
  •   abielita    7 年前

    你可以参考这个 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);
    
        2
  •  0
  •   Muneeb Akhtar    7 年前

    但是在使用教程时,我没有用代码更新我的应用程序名称。 教程代码为

     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快速启动”更新为“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
  •  0
  •   roman m    4 年前

    示例代码:

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