Google Drive API C# 83


Please Share

Google Drive APIHave you been trying to connect your website or application to Google Drive?  Would you like to see a list of files or a list of Directories stored on Google Drive?   Would you like to Upload a file to Google Drive or download a file from Google drive using C# .Net using Visual Studio.   In this tutorial series, we will be looking into the Google Drive API, using the Google .net Client library which makes accessing Google APIs much simpler.    There are a lot of things you can do with the Google Drive API, List files and folders,  Download files, Upload files, Change Files,  Copy files,  Delete Files, Trash Files,  Create directory’s, delete directory’s.  There is even a version of %appdata% on Google Drive where you can store your application specific files for each user.



I think you get the idea there are a lot of possibilities for us with Google drive.  My plans are to show you how to most of these work.

Five part Tutorial Series

  1. Google Drive API with C# .net – Authentication
  2. Google Drive API with C# .net – Files –  Files, directories, search
  3. Google Drive API with C# .net – Upload, update, patch, delete, trash
  4. Google Drive API with C# .net – Download
  5. Google Drive API with C# .net – File Permissions
  6. Google Drive API with C# .net – Sample project

Restringing your application.

Like with most of the Google APIs you need to be authenticated in order to connect to them. To do that you must first register your application on Google Developer console.   Under APIs be sure to enable the Google Drive API and Google Drive SDK, as always don’t forget to add a product name and email address on the  consent screen form.

Project Setup

Make sure your project is at least set to .net 4.0.

Add the following NuGet Package

PM> Install-Package Google.Apis.Drive.v2

Authentication

This tutorial assumes that you have already read the tutorial about Google Drive API with C# .net – Authentication. I will not be going into how to create a valid Drive service if you haven’t created one already please go read that tutorial then come back here.

List all of the files and directories

Now we want to get a list of all of the files and direcories on currently on our Google Drive account. In Google drive everything is a file, even directories.   The only difference is that the mime type for a directory is ‘application/vnd.google-apps.folder’.

List is just a way of getting back a list of everything that is currently on Google drive.

FilesResource.ListRequest request = service.Files.List();
FileList files = request.Execute();

This will bring back a list of all of the directories and files for the user that is currently authenticated. By default Google Drive will return to you a maximum of 100 items per page. You can set the the number of records returned per page up to 1000 by setting MaxResults.

FilesResource.ListRequest request = service.Files.List();
request.MaxResults = 1000;
FileList files = request.Execute();

But then you have a problem with what if you have more then 1000 files and directories on your Google Drive?   That’s where Nextpage comes into play. Please ignore the search paramator for a moment we will get to that in a minute.

 
/// 
        /// List all of the files and directories for the current user.  
        /// 
        /// Documentation: https://developers.google.com/drive/v2/reference/files/list
        /// Documentation Search: https://developers.google.com/drive/web/search-parameters
        /// 
        ///a Valid authenticated DriveService        
        ///if Search is null will return all files        
        /// 
        public static IList GetFiles(DriveService service, string search)
        {

            IList Files = new List();

            try
            {
                //List all of the files and directories for the current user.  
                // Documentation: https://developers.google.com/drive/v2/reference/files/list
                FilesResource.ListRequest list = service.Files.List();
                list.MaxResults = 1000;
                if (search != null)
                {
                    list.Q = search;
                }
                FileList filesFeed = list.Execute();

                //// Loop through until we arrive at an empty page
                while (filesFeed.Items != null)
                {
                    // Adding each item  to the list.
                    foreach (File item in filesFeed.Items)
                    {
                        Files.Add(item);
                    }

                    // We will know we are on the last page when the next page token is
                    // null.
                    // If this is the case, break.
                    if (filesFeed.NextPageToken == null)
                    {
                        break;
                    }

                    // Prepare the next page of results
                    list.PageToken = filesFeed.NextPageToken;

                    // Execute and process the next page request
                    filesFeed = list.Execute();
                }
            }
            catch (Exception ex) {
                // In the event there is an error with the request.
                Console.WriteLine(ex.Message);                            
            }
            return Files;
        }

The above method will continue to fetch files until there are no more and return the full list to you.


Parent Child

Files and directories can have parents and children.   The top level is Root so if the parent collection item has IsRoot set to true then you know you have hit the top.  (Note:Root is not actually returned in the list).  If you want to order things in a parent child tree.  All you need to do is look at the Parents collection on the file.

GoogleDriveParentChild

Search

There are a few issues with List.  First of all if the user has “trashed” the folder List is still going to return it.   This is where Search comes in,  before you execute your list add a “Q” to it.

request.Q = "trashed=false";

Another nice search is if you only want to return directories.

request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false";

You can link searches together with and. Here is a link to the Api reference for Search. Search For Files

Conclusion

You should now understand how to access the Google Drive API with an authenticated user. You should also understand the difference between a files and directories, how to get a list of all of the files currently on Google drive. I hope you will also agree that working with the Google APIs is quite easy once you get the authentication down. I hope this lesson was able to get you started on your Google Drive development.

Blog authors who like to make people happy and help them enjoy working with the Google APIs, release the code to go along with this tutorial on GitHub.

Please Share


Linda Lawton

About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as a developer and a database expert. I have been working with several of the Google APIs, since 2012. I helping others in the On-Line community to develop with the Google APIs, by creating my own blog www.daimto.com. This and my presence on a number of On-Line developer forums lead me to be noticed by the Google Analytics API development team. I was nominated for and recently became one of the first Google Developer Experts for Google Analytics.


Leave a comment

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

83 thoughts on “Google Drive API C#

  • Dan

    Just to let you know that your download script only pulls the metadata for the file. To download the actual file you need to use the DownloadUrl value from the metadata and use a webrequest as shown here https://developers.google.com/drive/web/manage-downloads#downloading_a_file I’m trying to figure out a way of authenticating the request when using a service account, if you have any ideas 🙂 http://stackoverflow.com/questions/23944974/unauthorized-response-when-downloading-file-with-service-account-in-google-drive

    • Administrator
      Linda Lawton

      Your Service account is off a little I think you need to create a GoogleDriveService. Once you have created the service you should be able to use the service to download the file. You shouldn’t need to be doing it though a HTTP Request.

      • Dan

        I was working through your entire blog post and everything went well (using an instance of DriveService) until I came to the download section. My DriveService is instantiated by:

        Google.Apis.Services.BaseClientService.Initializer cManager;
        cManager = CredentialManager.getCredentials();
        var service = new Google.Apis.Drive.v2.DriveService(cManager);

        using the getCredentials method detailed in my SO question.

        Using the following:

        FilesResource.GetRequest getFile = service.Files.Get(file.Id);
        System.IO.Stream stream = getFile.ExecuteAsStream();

        the metadata for the file was pulled in json format. It was at that point I reverted back to the google docs I linked to in my previous comment.

  • Jatinder

    Hi Linda,

    Thanks for sharing a wonderful post. I am new to Google Drive and have following scenarios for which I am not able to find anything (not sure if anything exists or not)
    –> I am creating a Windows app which will be SAAS based. Different Users will register and create their company logins and subusers under them. Now I want them to put the google drive credentials in one of the form and this should work for rest of the users. Currently the problem is that while development I got the google log in done and it never asks for the login again but when testing on a different system with different login, it keeps asking for google login. I simply want admin users to put their google drive credentials and it should work for upload and download files for all the users for that company.

    –> I want to keep versions of the same file (just like google drive does by default) on google drive. Lets say user A uploaded file xyz and then user B downloaded and changed file xyz and uploaded it on the drive again.
    I want 2 things here – only the changed content should get uploaded and not the whole file (this will save time for the user)
    2ndly I want to have history of the same file so I can show in my Windows application

    Thanks
    Jatinder

    • Administrator
      Linda Lawton

      If it was me i would have each company create a service account for the drive. Then you can allow the users to access the service account. Email me though the contact form if you want to chat about it.

      • Jatinder

        Hi Linda,

        Thank you very much for your answer. It has really helped me to resolve the first issue but I am still looking for options for the 2nd part of first point as well as 2nd point.

        I will re-phrase below

        –> I want my code to upload only the changed\added content so that it doesnt upload the whole file after user changed something
        –> I want to maintain history like how google docs do so I can give the users the option to revert back to a particular revision number

        By the way I sent you an email through the contact form, not sure if you received it.

        Thanks
        Jatinder

  • nisha

    Hello, I want to get the free space on Google drive on my service account in windows application. I search on this but could not find anything. Can you please help me in this.

  • Neeloy

    Hi Linda,
    In my opinion it is definitely the best article and solution you uploaded here. I have seen a lot of samples online but none can help but this sample. When I run the application and click on the button for the first time it opens the browser and the url is found like http://localhost:4297/authorize/ where the port is dynamic and I am confused with “authorize” keyword. Will you please help me understand the concept.

    May be I am wrong as I found nobody ask you this question. Thank you so much.

  • Sabyasachi Nanda

    I am trying to work on a web application using asp.net (with C#), that enables users to access files from their respective Google Drive. The code works perfectly in the native environment and I can view the files, and download them as per requirement. However, when I hoist it on the local server (IIS), the program does not work. It doesn’t redirect to the Google Authentication page as required. Worth mentions, while working on the local (native) system, I had used the client credentials for the native application and after hoisting it on the local server, I used the Client credentials for the web application (I also tried with the native credentials as well). Nothing seemed to work. Additionally, when I tried using
    the native credentials in the C# API run-time now it redirects to the authentication page but gives an error (redirect uri mismatch). Also, the redirect uri in the request keeps on changing every time I run the program. As informed now I am using Please help as I’m sure there is something I’m missing.

  • Sun

    HI I had a view of your many articles ,but I can.t find the “using Google.Apis.Services;”
    the new API dosen’t have the Google.Apis.Services ,what can i do

  • jose

    this is absolutely helpful, im wondering, is it possible to work with offline files ,,, i mean like create a google spreadsheet on the local google drive ? and also store to that file localy instead of online ?

    i have right now a basic program which creates a new .gsheet on drive online, but i want to be able to manage those files offline, create them and manage them offline, if i were to lose my internet. hope this makes sense

  • Jose

    i posted something and it seems it got deleted… i just want to know if its possible to use and create these spreadsheets being offline, is it possible ?

  • komal

    I am getting redirect uri mismatch error. Everytime I run the code it automatically generates redirect uri. Please help.

    • Administrator
      Linda Lawton

      When you run a web application though visual studio in a debug environment it automatically tacks on some random port. Normally this isn’t a problem but when trying to authenticate to the Google APIs it makes a mess of things

      You have two options.

      1. Set up your project so that it stops doing that.
      2. Create a Client ID for native application for testing locally, when you release your site to production switch back to using a Client ID for web application

  • Malik

    Hi @Linda I am also having a same Problem when I used client id for native application in debug mode its working, but when I use Client Id for Web Application in a release mode its just halt and new tab does not appear am I missing some thing?

    Please Help!
    Thanks in Advance

  • Jairo Franchi

    Hi Linda. I had answered here before and now I got my program working and I can see the files that are present on my GoogleDrive but I can use this Method Filelist and I can’t find anything about this. From what library it are coming?

    Thanks.

  • Michael B

    Linda, Great article !!!

    I have an ASP.NET application. I’m using the Google Picker in DocsView to allow the user to select one of their Google Drive files that when selected the ASP.NET will copy and share it to a number of other Google users from a list that is stored in the ASP.NET program. I have the selecting of the file finished and I am fixing to start the copy and share portion…

    Question1: I have generated a Web application OAuth Client ID. Should I have created a different OAuth Client ID (Service account or Installed application)?
    Question2: Is there already an example of what I described above with the mixing of Google Picker and Google Drive API in an ASP.NET app?
    Thanks in advance!!!

    • Administrator
      Linda Lawton

      ASP.net application should be Client ID for web application if you have any redirect uri issues while developing on location host you can switch to Client ID for native application, but remember to put it back to Client ID for web application before you release it to production.

      I don’t know of any sample projects that mix Google Picker and Google Drive API, sorry.

    • Administrator
      Linda Lawton

      I have never tried that before, have never seen it before either. I wonder if it has anything to do with the fact that the .dlls aren’t strong name signed, but this is just a guess.

      • Hyesun

        Thanks for replying. I’ve tried to sign those assembly with a strong name, but I failed, so I solved it in other way using embedding those .dll files as resources. Thank you for your help, again. May I ask one more question? So, the .exe file works fine alone without the .dll files, but when I tested it in other computer, it doesn’t run… I save all users log-in information (such as username and password) file in my google drive, and my application accesses the file to let user log in. I’m gonna change this log-in feature when I complete its web application, but for now I need to manage user log-in information using my google drive. I wanted to check other users can log in and use my application, so I tried to start the application in my other computer logged in my different google account. I saw the consent screen, but it seems like my application accesses my different google account’s google drive, not the drive contains the users log-in information file. If it’s true, would you like to give me some idea to make other users able to log in the application through accessing my google drive?

        • Administrator
          Linda Lawton

          Wait a week or so we are in the process of signing the client library now.

          You shouldn’t be saving users login and passwords. You should only be saving the refresh token, now that client login is shut down you have no use for there Google login and password you cant use it to access Google.

          • Hyesun

            Thank you so much for the news and the advice. I was struggle with the problem, but no problem with waiting for a week to me.

  • thomas

    Hi Linda. I really enjoy reading your blog.

    And I really appriciate that you are helping others use Googles APIs,
    since Google is not very good at documentation.

    I have a request though, could you make a step by step tutorial about how to use the Google Drive V2 REST API from c# ? that is, only using HTTP/HTTPS request directly to do everything… ?

    That way it should be possible to interact with Google Drive without having to lug around any Google DLL files or similar

    (all quickstart examples in c# seems to lug around a HUGE amount of Google DLL files)

    • Administrator
      Linda Lawton

      I agree the dlls are extensive, but i think it would be a lot of work to make a tutorial series on how to do everything with out the client library. I will consider it but no promises muli part upload is a pain without the library.

  • thomas

    Thanks for your reply.
    I have found it very difficult to find adequate information about how to form valid https requests to the Google Drive V2 REST API.

    I am currently doing to login flow using Javascript and then I connect to a webservice, that I am writing in c#, that then attempts to give me a list of the files stored on my Google Drive.

    But I keep getting a 403 forbidden. I suspect that this means that the authorization part is ok
    (I was getting 401 unauthorized before).

    Do you have any suggestions as to how I could proceed?

    Even better, an example of how my c# code for the GET request for the list command should look like?

    I am supplying the following header data (based on fiddler and many many google searches):

    request.UserAgent = “Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko”;
    request.Referer = “http://localhost/”;
    request.Headers.Add(“Origin”, “http://localhost/”);
    request.Headers.Add(“Authorization”, “Bearer ” + token);

    I am retrying the number of times and with the increasing number of wait times that google recommends when getting a 403.

    This is the web.config of my webservice…

    Again, thanks for your reply and any help you decide to provide me with.

    • Administrator
      Linda Lawton

      Sorry I cant help much with JavaScript. 403 forbidden normally has something to do with the fact the server just doesn’t like your request I don’t think you have even gotten to the authorization part.

  • Mohd Sherrez Kader

    Hi miss linda may i ask how do i get a specific folder and file from my drive so i can pass the a specifc folder value into the upload methid and download specific files too ,

    leaving the string search to be empty returns everything,tried to look into Documentation Search: https://developers.google.com/drive/web/search-parameters but no luck could you help please?

    what do we have to put in the string search to achieve it

  • Md Nurezaman

    Hi, Linda. Thanks for the amazing tutorial. However, I have a problem. When I try to list the files, only the default Getting Started pdf gets listed. Other uploads that I have made(directly into drive) are ignored. I am using a service account. Thanks in advance

  • Atif Ahmed Mirza

    Hi,

    I am trying to use google api to give user an option to select a file using the google picker and then use the selected file to download it. I can get the access token using the picker sample code in javascript and the file id. I wanted to now how can i download file using the access token.

    The code you have given above create the ‘credential; using the code below:
    var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId,
    ClientSecret = clientSecret},
    scopes,
    Environment.UserName,
    CancellationToken.None,
    new FileDataStore(“Daimto.GoogleDrive.Auth.Store”)).Result;

    and then this credential is used to create drive service.

    I s there any way to create drice service using access token??

    Regards,
    Atif

    • Linda Lawton
      Linda Lawton Post author

      I have a sample project built for V3. I have unfortunately been hit with the Flu and haven’t had the energy to write up a tutorial series on it yet.

      As soon as my energy returns i will get on it. At the very leased i could upload the sample project to GitHub.

  • Akshita Gupta

    How do you search for a particular fileId using Q property?
    Usecase: Uploaded a file and got the responseBody. With v3 api, we need to specify the fields. So after response body, i make a get request of files and use Q property for that Id to give me requested fields like webViewLink etc.

    So For file Id=xxxxxxx

    listRequest.Q = “fileId=’fileId’ ” doesn’t work, throws exception. Coul dyou please correct me here?

    • Akshita Gupta

      Hi Lynda, So in the above post, i figured out the syntax error where i am not using string.format. So my modified queries are below:
      listRequest.Q = string.Format(“id='{0}’ “, _fileId);
      I also tried listRequest.Q = string.Format(“id in ‘{0}’ “, _fileId); and listRequest.Q = string.Format(“‘{0}’ contains id”, _fileId); But none worked. Kindly guide me here.

  • Aditya

    Hi,
    I am new to Google Drive.. I am trying to do a Google authentication using Google Drive API through javascript. I have added the clientId in my code which is created from the Google server. It is responding me with a “Origin Mismatch” error. Am i missing anything in the configuration?

    • Linda Lawton
      Linda Lawton Post author

      I am not a javascript programer and my javascript is very rusty so i cant be of much help. try posting your question on stackoverflow.com someone there will be able to help you. I can tell you that origin missmatch is an issue with what ever you put in javascript origin in google developer console and the page you are sending the request from. They must match.

      • Aditya

        Right.. problem was with the origin. Actually in the google documentation they had given http://localhost which din work out for me. Changed it to localhost ip 127.0.0.1 and it worked. Wondering why localhost din work as per google documentation. Let me know if you know the reason. Anyways thanks for your answer 🙂

  • Gopal Biswas

    I’m trying to develop the google service account and it works fine for me.
    I have mailed you some times ago for a problem and I think I have resolved the issue. The service account “Service account ID” is working as serviceAccountEmail.
    One problem I’m facing now, Suppose a folder has created in google drive named “UploadDocs” and I’m uploading files under this folder. The files are uploaded inside the folder successfully but I couldn’t see those uploaded files at all. Is this happening for permissions for the folder “UploadDocs”? What is the process to give full permission to the folder “UploadDocs”?

    Please help.

    • Linda Lawton
      Linda Lawton Post author

      I think its an issue with permissions in drive. From what i remember if you upload a file into a folder it doesn’t necessarily get the permissions applied of the folder you need to insert permissions to the file itself AFTER you upload it.

        • Gopal Biswas

          I want to confirm 1 more thing from you. Is there any storage limitation for google drive service account or I could increase the storage capacity as required?

          • Gopal Biswas

            I want to paginate the Google Drive files using Google Drive api client library in ASP.Net C#. I’m following your article of Google Drive Service account. Suppose there are 100 files in my google drive account.How could I paginate these files like 10 records for each page.

  • George Kamau

    Hi Linda,

    I have followed your tutorials plus the documentation by google and have been able to upload and set permissions successfully. Thank you for the tutorials.

    However am having a challenge in trying to set a custom email message while sharing a file. I have tried to follow the documentation but still cant be able to set the message. Might you have an example for setting the custom email message.

    Thanks in advance.

    Regards,

    GK-59.

    • Linda Lawton
      Linda Lawton Post author

      I have seen quite a few people with this problem and i have not been able to get it to work either. I would post your question on stackoverflow make sure to tag it Google-drive-sdk and Google-apis-dotnet-client

  • Jan

    Good day maam!
    I have a question.
    Is it possible to view an image picture on my Application in the google drive even though Not downloading the picture?

  • Jan

    Hi maam linda!
    I am trying to create a folder in my google drive to save all images file.
    Is there a way to set a specific folder to search a file ?
    I am resulting 0 count when i am trying to get all files
    thanks ahead

  • sertom

    Hi, Thanks for that post.

    I need create an application that monitors real-time google drive online, are you have any tips on how to do it?

  • umar memon

    Hello,
    How can i manage the Google Form the same way we can manage the google docs files from asp .net application.
    Any other api for that?
    Thanks in advance.