Bikramjeet Singh
Bikramjeet Singh

Reputation: 186

Null response creating file using Google Drive .NET API

I am trying to upload a file onto my Drive using Google Drive .NET API v3. My code is below

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

    public ActionResult Index()
    {
        UserCredential credential;

        using (var stream =
            new FileStream("C:/Users/admin1/Documents/visual studio 2017/Projects/TryGoogleDrive/TryGoogleDrive/client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = 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;
            Debug.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;
        Debug.WriteLine("Files:");
        if (files != null && files.Count > 0)
        {
            foreach (var file in files)
            {
                Debug.WriteLine("{0} ({1})", file.Name, file.Id);
            }
        }
        else
        {
            Debug.WriteLine("No files found.");
        }

        var fileMetadata = new Google.Apis.Drive.v3.Data.File()
        {
            Name = "report.csv",
            MimeType = "text/csv",
        };
        FilesResource.CreateMediaUpload request;
        using (var stream = new FileStream("C:/debugging/report.csv",
                                FileMode.Open))
        {
            request = service.Files.Create(
                fileMetadata, stream, "text/csv");
            request.Fields = "id";
            request.Upload();
        }
        var response = request.ResponseBody;
        Console.WriteLine("File ID: " + response.Id);

        return View();        
    }

The problem I'm facing is that response is always null. I looked into it a bit further and found that the request returned a 403 resultCode. I also took a look at some other questions on SO this and this but neither were of any help.

Edit: I forgot to mention that the first part of the code is working correctly - it lists all the files in my Drive. Only the second part is not working (the upload file part)

Upvotes: 0

Views: 2483

Answers (4)

kuldeep chopra
kuldeep chopra

Reputation: 782

    string[] Scopes = { DriveService.Scope.Drive };
  • Change the Drive scope then delete the file token.json
  • in vs2017 you can see token.json file in token.json folder when client_secret.json file present.

click to see token.json

Upvotes: 1

Hardik Patel
Hardik Patel

Reputation: 115

Change static string[] Scopes = { DriveService.Scope.DriveReadonly }; to static string[] Scopes = { DriveService.Scope.Drive };.

After changes, take a look into token.json file and check does it change its scope from DriveReadonly to Drive.

If you are seeing DriveReadonly then delete the token.json file and run the application again.

Upvotes: 0

Ben Thompson
Ben Thompson

Reputation: 1

Have a look at what request.Upload() returns. For me when I was having this issue it returned:

Insufficient Permission Errors [Message[Insufficient Permission] Location[ - ]

I changed my scope from DriveService.Scope.DriveReadonly to DriveService.Scope.Drive and I was in business.

Upvotes: 0

MαπμQμαπkγVπ.0
MαπμQμαπkγVπ.0

Reputation: 6737

Try to visit this post from ASP.NET forum.

The same idea as what you want to do in your app, since you are dealing with uploading a file in Google Drive using .net.

You may try to call rest api directly to achieve your requirement :

The quickstart from .net will help you to make requests from/to the Drive API.

Upload Files:

The Drive API allows you to upload file data when create or updating a File resource.

You can send upload requests in any of the following ways:

  • Simple upload: uploadType=media. For quick transfer of a small file (5 MB or less). To perform a simple upload, refer to Performing a Simple Upload.
  • Multipart upload: uploadType=multipart. For quick transfer of a small file (5 MB or less) and metadata describing the file, all in a single request. To perform a multipart upload, refer to Performing a Multipart Upload.
  • Resumable upload: uploadType=resumable. For more reliable transfer, especially important with large files. Resumable uploads are a good choice for most applications, since they also work for small files at the cost of one additional HTTP request per upload. To perform a resumable upload, refer to Performing a Resumable Upload.

You may try this code from the documentation on uploading sample 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);

You may check the errors you may encounter in this documentation.

Upvotes: 0

Related Questions