Google Drive API with C# .net – Download 43


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 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 *

43 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.