1

It's my first time to use API in C#. I'll be using the API to upload the video I recorded from a webcam.

Here's what I did:

  1. Added Google.Apis.Drive.v3 package using NuGet
    Result: Installed
  2. Followed .NET Quickstart on Google Drive APIs
    I added the code to Program.cs
    Result: It worked!

I don't know the next step. I read Performing Simple Upload but I don't know where to place the code.

I created a function upload() but var, new File(), Name, and driveService gets an error--something about System.IO.File but I can't find a package with this name and the driveService does not exist

I followed other tutorials like 40049021 and 1228046 but I keep on getting an errors and they don't use what's recommended on v3.

Here's my Program.cs:

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;
using System.Windows.Forms;

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

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

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.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:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine("{0} ({1})", file.Name, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

EDIT: This is the 'Basic Upload' code provided by Google:

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

Please help me on how to create a function to upload file(.jpg and .avi)

EDIT2: This is what the code I use to test

static void InitializeGAPI()
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.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:");
            //if (files != null && files.Count > 0)
            //{
            //    foreach (var file in files)
            //    {
            //        Console.WriteLine("{0} ({1})", file.Name, file.Id);
            //    }
            //}
            //else
            //{
            //    Console.WriteLine("No files found.");
            //}
            //Console.Read();

            string uploadfile = @"C:\Users\iya\Desktop\tmp\Image-2019-01-31_10-25-32-AM.jpg";

            if (System.IO.File.Exists(uploadfile))
            {
                MessageBox.Show("Uploading..." + uploadfile);                 

                var fileMetadata = new Google.Apis.Drive.v3.Data.File();
                fileMetadata.Name = System.IO.Path.GetFileName(uploadfile);
                fileMetadata.MimeType = GetMimeType(uploadfile);
                //fileMetadata.Parents = new List<string> { "Test Folder" };

                FilesResource.CreateMediaUpload request;
                try
                {
                    using (var stream = new System.IO.FileStream(uploadfile, System.IO.FileMode.Open))
                    {
                        request = service.Files.Create(fileMetadata, stream, fileMetadata.MimeType);
                        request.Fields = "id";
                        request.Upload();

                    }
                    var file = request.ResponseBody;
                    var fili = file.Id;
                    Console.WriteLine("File ID: " + file.Id);
                }
                catch (Exception e)
                {
                    MessageBox.Show("An error occurred: " + e.Message);
                }
            }
            else
            {
                MessageBox.Show("File does not exist: " + uploadfile);
            }

        }

What should be my ApplicationName?

IyaSheep
  • 43
  • 1
  • 1
  • 10
  • What is the error you are encountering? The solution for 1228046 should be enough to answer your question. – Mr.Rebot Feb 01 '19 at 10:26
  • 1
    "Object reference not set to an instance of an object". But the file exist – IyaSheep Feb 13 '19 at 07:08
  • @Mr.Rebot No the solution for 1228046 is NOT an adequate answer - it is vague and the code doesn't even work properly. Tutorials for this topic are horrible and incomplete for beginners. – ChrisUK Apr 01 '19 at 15:11

0 Answers0