Google Drive V3 About


Please Share

google drive Are you working on an application that needs to check how much space a user has left on their Google Drive account. Would you like to find the name of your currently authenticated user? or possibly their email address? This information can be found in the Google Drive API v3 About method. I am going to show you how to find this information using C# and the Google .Net Client library.

About.Get



The About Get method Gets information about the user, the user’s Drive, and system capabilities. In order to use this method you must be authenticated with one of the following scopes.

      https://www.googleapis.com/auth/drive
      https://www.googleapis.com/auth/drive.file
      https://www.googleapis.com/auth/drive.readonly
      https://www.googleapis.com/auth/drive.metadata.readonly
      https://www.googleapis.com/auth/drive.appdata
      https://www.googleapis.com/auth/drive.metadata
      https://www.googleapis.com/auth/drive.photos.readonly

Prerequisite

The first thing we will need to do is import the Google Drive API v3 NuGet package

Install-Package Google.Apis.Drive.v3

Authenticate

About data is private data which means it is owned by a user. In order to access it you must be authenticated to that user.


        /// <summary>
        /// This method requests Authentcation from a user using Oauth2.  
        /// Credentials are stored in System.Environment.SpecialFolder.Personal
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
        /// <param name="userName">Identifying string for the user who is being authentcated.</param>
        /// <returns>DriveService used to make requests against the Drive API</returns>
        public static DriveService AuthenticateOauth(string clientSecretJson, string userName)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(clientSecretJson))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(clientSecretJson))
                    throw new Exception("clientSecretJson file does not exist.");

                // These are the scopes of permissions you need. It is best to request only what you need and not all of them
                string[] scopes = new string[] { DriveService.Scope.DriveReadonly};         	//View the files in your Google Drive                                                 
                UserCredential credential;
                using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                    // Requesting Authentication or loading previously stored authentication for userName
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credPath, true)).Result;
                }

                // Create Drive API service.
                return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Oauth2 Authentication Sample"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create Oauth2 account DriveService failed" + ex.Message);
                throw new Exception("CreateServiceAccountDriveFailed", ex);
            }
        }

Request Data

Now that we have authenticated our user we will be able to access their data.

  
        /// <summary>
        /// Gets information about the user, the user's Drive, and system capabilities. 
        /// Documentation https://developers.google.com/drive/v3/reference/about/get
        /// Generation Note: This does not always build correctly.  
        /// Google needs to standardize things I need to figure out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated drive service.</param>  
        /// <returns>AboutResponse</returns>
        public static About AboutGet(DriveService service)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");

                // Make the request.
                var request = service.About.Get();
                request.Fields = "user ";
                
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request About.Get failed.", ex);
            }
        }

Display Data

Now we can check the data that is returned.

      var data = AboutGet(service);
            Console.WriteLine("User:");
            PropertyInfo[] properties = typeof(Google.Apis.Drive.v3.Data.User).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                Console.WriteLine("{0} = {1}", property.Name, property.GetValue(data.User, null));
            }

            Console.WriteLine("StorageQuotaData:");
            properties = typeof(Google.Apis.Drive.v3.Data.About.StorageQuotaData).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                Console.WriteLine("{0} = {1}", property.Name, property.GetValue(data.StorageQuota, null));
            }

Conclusion

It can be a good idea to check that a user has space on their drive account before attempting to upload a file. If the user is out of space then you will get an error sometime during your upload process.

Please Share


Linda Lawton

About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *