使用 google 驱动器 api v3 C# 上传文件或创建文件夹

File upload or folder creation using google drive api v3 C#

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

    }   
}  

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

时保持为 Null

你可以参考这个。确保您传递的范围正确。

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

问题是我在使用教程时创建应用程序时我的应用程序名称是 "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

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

示例代码:

var progress = request.Upload();

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