Google Drive API with C# .net – Download 49


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.



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.
Now we have a drive service that we can preform perform though.

Download

In  order to download a file we need to know its file resorce the only way to get the file id is from the Files.List() command we used earlier.

/// 
        /// Download a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/get
        /// 
        /// a Valid authenticated DriveService
        /// File resource of the file to download
        /// location of where to save the file including the file name to save it as.
        /// 
        public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
        {

            if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
            {
                try
                {
                    var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
                    byte[] arrBytes = x.Result;
                    System.IO.File.WriteAllBytes(_saveTo, arrBytes);
                    return true;                  
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return false;
                }
            }
            else
            {
                // The file doesn't have any content stored on Drive.
                return false;
            }
        }

Using _service.HttpClient.GetByteArrayAsync we can pass it the download url of the file we would like to download. Once the file is download its a simple matter of wright the file to the disk.

Conclusion

You should now understand how to access the Google Drive API with an authenticated user. You should also be able to download a file from 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 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 *

49 thoughts on “Google Drive API with C# .net – Download

  • Vaibhav Jain

    Hi,
    I am trying to integrate GoogleDocs UI with our ASP.NET Web application, in this files are stored on our file storage.
    We want to open Google Docs Editor to edit the word/excel/PPT files.

    As a part of POC for this requirement I am doing below:
    1) Uploading file into Google Drive using below code:
    Dim objInsert As Google.Apis.Drive.v2.FilesResource.InsertMediaUpload = objDriveService.Files.Insert(objFile, objStream, sMimeType)
    objInsert.Convert = True
    objInsert.Upload()

    2) Getting response after upload and using objFile.AlternateLink property to open the Editor to edit file.

    3) I am facing the issue to download the file when I am using objInsert.Convert = True.
    when I am making the call to File object my Download URL (objFile.DownloadUrl) is not returning it is set with Null.
    If I don’t use the objInsert.Convert = True then I am getting Download URL but problem is then AlternateLink open the file in View mode with various option, I want the URL to open it directly in editor.

    Please suggest what am I missing here.

  • Alex More

    Thank you, everything works.But cant see files and folders in Google Drive on my Google account in browser created by the sample?

  • Jairo Franchi

    Hi there. I’m trying to create a C# Program that will get all the files on Google Drive for a certain user but I don’t know how to start. I tried to do what you said there but seems that not work. What you suggest me to start this development. I already created an automation program that downloaded a lot of files from a website with authentication but for Google Drive seems not so simple.

    Thanks for now.

      • Jairo Franchi

        I added the first block of code of this link and I replaced the ClientID by the ClientID generated in the Google Developers Console and I changed the ClientSecret by the Certificate Fingerprints generated. Is that right what I am doing? I get this message when I try to run the application:

        Error: redirect_uri_mismatch

        The redirect URI in the request: http://localhost:65405/authorize/ did not match a registered redirect URI.

        Thanks!

          • Jairo Franchi

            I tried exactly this, I changed the Redirect URI on Google Developer Console but every time I run my application seems that the URL is changing so doens’t matters what I add to the Redirect URI on Google Console.
            What am I doing wrong?

          • Administrator
            Linda Lawton

            Visual studio likes to change the port in development. You have a few options fix the project in the settings so it doesn’t do that. Or create a Client ID for native application to test on localhost. Once you go to production switch it back to a Client ID for web application

  • Brant

    Although you show how to download a non-google docs file, could you share a snippet which shows how to export a google spreadsheet doc to say, csv?
    Thanks!

  • denise michelle

    Hi. i am just testing some code. i have successfully uploaded a file. now i want to download that file.
    I have checked the permissions and everything is good. why am i getting a permission error?
    Access to the path ‘C:\inetpub\testpage\Downloads’ is denied.

    var stream = service.HttpClient.GetStreamAsync(downloadUrl);
    var result = stream.Result;
    using (var fileStream = System.IO.File.Create(Server.MapPath(“~/Downloads”)))
    {
    result.CopyTo(fileStream);
    }

    also tried this same error:
    var stream = service.HttpClient.GetByteArrayAsync(downloadUrl);
    byte[] arrBytes = stream.Result;
    System.IO.File.WriteAllBytes(Server.MapPath(“~/Downloads”), arrBytes);

    does anyone know what i am missing?

    • denise michelle

      never mind. i just needed the filename. i guess i have to save both the download url and the original filename properties.

      • denise michelle

        took it a step further and force download the file:
        public void DownloadFile(File file)
        {

        var stream = service.HttpClient.GetByteArrayAsync(file.DownloadUrl);
        byte[] arrBytes = stream.Result;

        Response.ClearContent();
        Response.ClearHeaders();
        Response.Buffer = true;
        Response.ContentType = file.MimeType;
        Response.AddHeader(“Content-Length”, arrBytes.Length.ToString());
        Response.AddHeader(“Content-Disposition”, “attachment; filename=” + file.OriginalFilename);
        Response.BinaryWrite(arrBytes);
        Response.Flush();
        Response.End();

        }

  • Jaidev Khatri

    var stream = service.HttpClient.GetByteArrayAsync(file.DownloadUrl);

    System.NullReferenceException was caught
    HResult=-2147467261
    Message=Object reference not set to an instance of an object.
    Source=System.Net.Http
    StackTrace:
    at System.Net.Http.Headers.HttpRequestHeaders.AddHeaders(HttpHeaders sourceHeaders)
    at System.Net.Http.HttpClient.PrepareRequestMessage(HttpRequestMessage request)
    at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
    at System.Net.Http.HttpClient.GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
    at System.Net.Http.HttpClient.GetContentAsync[T](Uri requestUri, HttpCompletionOption completionOption, T defaultValue, Func`2 readAs)
    at System.Net.Http.HttpClient.GetByteArrayAsync(Uri requestUri)
    at System.Net.Http.HttpClient.GetByteArrayAsync(String requestUri)

    Really don’t know where is the mistake.

  • Nutan Patel

    Hello,

    Thanks for sharing such a nice article!
    I am facing one issue. I want to download each worksheets of spreadsheet using new google drive api 2. My previous code was using SpreadSheet API, how can I do the same code using google drive api 2. Google Drive API treats every objects as File and I can not find worksheets under File objects.

    Also to download worksheet, I need GID of that worksheet. Where can I find that GID. ?

    Please do needful.

    Thanks
    Nutan Patel

    Thanks
    Nutan Patel

    • Linda Lawton
      Linda Lawton Post author

      you can use files.list with the q option to search for just sheets mimeType=’application/vnd.google-apps.spreadsheet’

      I havent used the Google sheets api much, but i would think once you check the file you can get a list of worksheets.

  • harikrishna parmar

    how to download google doc file from google drive??
    this code is only for user files.. which is not created in google docs.
    whats about google docs??

  • soa

    Hey Linda,

    Nice article. I managed to setup few functionalities up and running however I got stuck with download. I keep having an exception:

    File file = service.Files.Get(“testFile”).Execute(); // This is the line that throws the exception

    The exception:

    File not found: “testFile” [404]
    Errors [
    Message[File not found: testFile]
    Location[file – other]
    Reason[notFound]
    Domain[global] ]

    The testFile is a simple .txt file that I have previously uploaded via my client.

    Am I initializing the File object in a correct way? Notice that I pass the name of the file as file id – I guess the id stands for the file title.

    Any help would be much appreciated!

    Thanks!

    • Linda Lawton
      Linda Lawton Post author

      You need to get the file id not the file name.

      File file = service.Files.Get(fileid).Execute();

      Try using files.list to find all the files and get the file id you are looking for.

    • Velu

      Dear all,
      I am getting in service null after authentication.
      if (service == null)
      {
      Console.WriteLine(“Authentication error”);
      Console.ReadLine();
      }

  • John

    Hi Linda,
    If I my web application upload a Microsoft Word document via the Drive API (service account), can my web application then open the file in Microsoft Word via the Drive API (service account)? Or, will the users of my web application have to click on the file to download the Word document and then have to open it using Word?

    I’d really like to avoid the 2 step process of downloading and then opening it.

    Thanks

    • Linda Lawton
      Linda Lawton Post author

      First if you are uploading the file to the service accounts drive account there is no web version to access. When you open a file “on” drive its open in the web application. I suspect the service account will need to download it and send it to your user they can then open it on there machine.

  • madhan

    Hi
    it was great and simple… But i have one doubt
    if i have uploaded multiple documents in to google drive API after that can i download one particular document through API , is this possible … !
    please Help me
    Thanks in Advance…..!

  • Vinay

    Hi Linda,

    Nice article. It works like a charm. Is there any possibility of downloading multiple (may be based on id or based on download url from drive) files as a single zip file? I can download multiple files from Google Drive ui by dragging the needy files and clicked downloaded its prompting as zip file download but how to do pro-grammatically using C#.

    Thanks,
    Vinay

    • Linda Lawton
      Linda Lawton Post author

      As far as i know drive doesn’t support you can only download one file at a time. Its probably something you could code yourself download each file then zip them. However that would assume you have some kind of web application you would be downloading the files to your web server then zipping them and sending them on to the user.

  • Moymoy

    Hello maam, I just want to know where I can find the downloaded file?

    It only shows on my C# console that it is downloaded. But the question is where is the downloaded file.

    Thanks.

  • Alessandro Spina

    Hi there,
    thanks in advance for the great job.
    I’m in trouble with google drive authentication. I’m going to explain my issue: I’m writing a program that allow to upload/download files to/from a google drive personal account.
    With the code below everytime I run the program I grant the access to the app always to the same user

    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = “xxx”, .ClientSecret = “xxx”}, {DriveService.Scope.Drive}, “user”, CancellationToken.None).Result
    service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential, .ApplicationName = “test”})

    How can I grant the access for each personal google account that want to use my program?

    I hope in your help! 🙂

    • Linda Lawton
      Linda Lawton Post author

      Each user will have to authenticate your application granting you access to their google drive account. Credentials are stored in %appData% on your machine denoted by the “user” parameter you are sending. Depending upon which user you want to access you just need to swap the “user” pram to access their credentials. This may help Google .net – FileDatastore demystified

      • Alessandro Spina

        Thanks a lot, Linda! ^_^
        Now I get it, but I’ve some other questions. May I bore you? …I hope yes! 🙂

        I’m seeing that there’s an expiration time and my idea was that I can store the access_token (or the refresh_token) in a database, so the user (that already has accessed) can avoid a new access to google. Is it a good approch? Can you indicate me the right way?

        Thanks for the help,
        best regards.

        • Linda Lawton
          Linda Lawton Post author

          I am always happy to answer interesting questions and interesting questions never bore me.

          Access tokens are short lived you have an hour before it will need to be refreshed. (Note: The library handles refreshing for you).

          You can store the fresh token in your database so that you can access it when needed. Basically you wont be using fileDatastore you will need to create your own implementation of iDatastore. Check this Gist it should give you a head start depending upon which database you are using.