Before we start this article we must know about Google Drive API.
What is Google REST API?
Google REST API is a set of Application Programming Interfaces (APIs) developed by Google which allow communication with Google services and their integration with other services. Examples of these includes Search, Gmail, Google Drive & much more.
What is a REST API?
Here, REST stands for Representational State Transfer. This type of API relies on stateless, client-server, cacheable communication protocols, and Rest APIs commonly use HTTP protocols.
Introduction to Google Drive API Version 3
Google Drive API is one of the most popular APIs. Users can integrate Google drive with their apps through APIs. There are many apps available for collaborative document creating, editing (Google Docs, Sheets) and storing their personal or official documents.
So, Google Drive API enables you to store and access user data from apps on any platform.
Step 1
Log into your Google account.
Step 2
Register your application in Google API Console from
here this URL.
Step 3
Create a new project by clicking on the "Continue" button.
Step 4
Click on the "Cancel" button.
Step 5
Go to "OAuth consent screen".
Step 6
Enter the application name and click "Save".
Click on the"OAuth consent screen" option on the menu. Now, your logged email address will appear and you need to type your product name in "Product name shown to users" text box. Now, click on the "Save" button.
Step 7
Go to the Credentials >> OAuth client ID.
Step 8
Select the web application and click on the "Create" button.
Step 9
Download the OAuth 2.0 Client Id’s file.
This file includes client ID, Client secret id, project_id, auth_uri, token_uri, redirect_uris, etc. which are used to integrate your Google Drive with the project.
Google automatically saves this OAuth 2.0 Client ID & Client secret id in a .json (JavaScript Object Notation) format file. Please download this .json file (client_secret.json).
This file contains clients information.
These are,
- client id,
- client secret id,
- project_id
- auth_uri,
- token_uri
- redirect_uris
This information is extremely useful for every time your application communicates with Google Drive APIs.
Step 10
Copy this file into the root folder of your project. Now, right-click this file and go to the property and select "Copy always" in "Copy to Output Directory" option.
Step 11 - Install the NuGet package
Opening the NuGet Package Manager Console, select the package source and run these following two commands.
- Install-Package Google.Apis.Drive.v3
- Install-Package Google.Apis.Drive.v2
Step 12
Write this code to get permissions for your application. Give the path where you want to save the Access Token file.
Step 13
Create a Method for getting all drive files, folders, downloaded files, deleted files, and moved files. Rename file, upload files in a folder, create a folder in another folder, etc.,
Before I continue this, we need to know some key concepts of Google Drive. The key concepts are:
Google Drive creates a unique ID for each & every item in the drive.
We create and upload the same name folders and files multiple times in the same location in Google drive. Google drive has identified this item by the unique IDs.
When creating a folder in Google Drive, just like a file, Google Drive provides a specific unique folder id for the newly created folder. But in this case, we need to provide MIME type for the folder "application/vnd.google-apps.folder".
Please see this code.
- public static void CreateFolderOnDrive(string Folder_Name)
- {
- Google.Apis.Drive.v3.DriveService service = GetService_v3();
-
- Google.Apis.Drive.v3.Data.File FileMetaData = new
- Google.Apis.Drive.v3.Data.File();
- FileMetaData.Name = Folder_Name;
- FileMetaData.MimeType = "application/vnd.google-apps.folder";
-
- Google.Apis.Drive.v3.FilesResource.CreateRequest request;
-
- request = service.Files.Create(FileMetaData);
- request.Fields = "id";
- var file = request.Execute();
- }
When you want to upload a file in the specific folder, you must specify the correct folder id in the parent property of the Google Drive file.
Please see this code.
- public static void FileUploadInFolder(string folderId, HttpPostedFileBase file)
- {
- if (file != null && file.ContentLength > 0)
- {
- Google.Apis.Drive.v3.DriveService service = GetService_v3();
-
- string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
- Path.GetFileName(file.FileName));
- file.SaveAs(path);
-
- var FileMetaData = new Google.Apis.Drive.v3.Data.File()
- {
- Name = Path.GetFileName(file.FileName),
- MimeType = MimeMapping.GetMimeMapping(path),
- Parents = new List<string>
- {
- folderId
- }
- };
- Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
- using (var stream = new System.IO.FileStream(path,
- System.IO.FileMode.Open))
- {
- request = service.Files.Create(FileMetaData, stream,
- FileMetaData.MimeType);
- request.Fields = "id";
- request.Upload();
- }
- var file1 = request.ResponseBody;
- }
- }
After creating .cs file, add all the below references for Google API to use.
- using Google.Apis.Auth.OAuth2;
- using Google.Apis.Download;
- using Google.Apis.Drive.v2;
- using Google.Apis.Drive.v3;
- using Google.Apis.Services;
- using Google.Apis.Util.Store;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading;
- using System.Web;
- public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.Drive};
-
-
- public static Google.Apis.Drive.v3.DriveService GetService()
- {
-
- UserCredential credential;
- var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/");
-
- using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
- {
- String FolderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/"); ;
- String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");
-
- credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
- GoogleClientSecrets.Load(stream).Secrets,
- Scopes,
- "user",
- CancellationToken.None,
- new FileDataStore(FilePath, true)).Result;
- }
-
-
- Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
- {
- HttpClientInitializer = credential,
- ApplicationName = "GoogleDriveRestAPI-v3",
- });
- return service;
- }
-
- public static Google.Apis.Drive.v2.DriveService GetService_v2()
- {
- UserCredential credential;
- var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/");
-
- using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
- {
-
- String FilePath = Path.Combine(CSPath, "DriveServiceCredentials.json");
-
- credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
- GoogleClientSecrets.Load(stream).Secrets,
- Scopes,
- "user",
- CancellationToken.None,
- new FileDataStore(FilePath, true)).Result;
- }
-
-
- Google.Apis.Drive.v2.DriveService service = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer()
- {
- HttpClientInitializer = credential,
- ApplicationName = "GoogleDriveRestAPI-v2",
- });
- return service;
- }
-
-
- public static List<GoogleDriveFile> GetDriveFiles()
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
-
-
- Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();
-
-
- FileListRequest.Fields = "nextPageToken, files(*)";
-
-
- IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
- List<GoogleDriveFile> FileList = new List<GoogleDriveFile>();
-
-
-
-
-
-
- if (files != null && files.Count > 0)
- {
- foreach (var file in files)
- {
- GoogleDriveFile File = new GoogleDriveFile
- {
- Id = file.Id,
- Name = file.Name,
- Size = file.Size,
- Version = file.Version,
- CreatedTime = file.CreatedTime,
- Parents = file.Parents,
- MimeType = file.MimeType
- };
- FileList.Add(File);
- }
- }
- return FileList;
- }
-
-
- public static void FileUpload(HttpPostedFileBase file)
- {
- if (file != null && file.ContentLength > 0)
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
-
- string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
- Path.GetFileName(file.FileName));
- file.SaveAs(path);
-
- var FileMetaData = new Google.Apis.Drive.v3.Data.File();
- FileMetaData.Name = Path.GetFileName(file.FileName);
- FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);
-
- Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
-
- using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
- {
- request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
- request.Fields = "id";
- request.Upload();
- }
-
-
-
-
-
- }
- }
-
-
- public static string DownloadGoogleFile(string fileId)
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
-
- string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");
- Google.Apis.Drive.v3.FilesResource.GetRequest request = service.Files.Get(fileId);
-
- string FileName = request.Execute().Name;
- string FilePath = System.IO.Path.Combine(FolderPath, FileName);
-
- MemoryStream stream1 = new MemoryStream();
-
-
-
-
- request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
- {
- switch (progress.Status)
- {
- case DownloadStatus.Downloading:
- {
- Console.WriteLine(progress.BytesDownloaded);
- break;
- }
- case DownloadStatus.Completed:
- {
- Console.WriteLine("Download complete.");
- SaveStream(stream1, FilePath);
- break;
- }
- case DownloadStatus.Failed:
- {
- Console.WriteLine("Download failed.");
- break;
- }
- }
- };
- request.Download(stream1);
- return FilePath;
- }
-
-
- private static void SaveStream(MemoryStream stream, string FilePath)
- {
- using (System.IO.FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
- {
- stream.WriteTo(file);
- }
- }
-
-
- public static void DeleteFile(GoogleDriveFile files)
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
- try
- {
-
- if (service == null)
- throw new ArgumentNullException("service");
-
- if (files == null)
- throw new ArgumentNullException(files.Id);
-
-
- service.Files.Delete(files.Id).Execute();
- }
- catch (Exception ex)
- {
- throw new Exception("Request Files.Delete failed.", ex);
- }
- }
-
- public static List<GoogleDriveFile> GetContainsInFolder(String folderId)
- {
- List<string> ChildList = new List<string>();
- Google.Apis.Drive.v2.DriveService ServiceV2 = GetService_v2();
- ChildrenResource.ListRequest ChildrenIDsRequest = ServiceV2.Children.List(folderId);
-
-
-
- do
- {
- var children = ChildrenIDsRequest.Execute();
-
- if (children.Items != null && children.Items.Count > 0)
- {
- foreach (var file in children.Items)
- {
- ChildList.Add(file.Id);
- }
- }
- ChildrenIDsRequest.PageToken = children.NextPageToken;
-
- } while (!String.IsNullOrEmpty(ChildrenIDsRequest.PageToken));
-
-
- List<GoogleDriveFile> AllFileList = GetDriveFiles();
- List<GoogleDriveFile> Filter_FileList = new List<GoogleDriveFile>();
-
- foreach (string Id in ChildList)
- {
- Filter_FileList.Add(AllFileList.Where(x => x.Id == Id).FirstOrDefault());
- }
- return Filter_FileList;
- }
-
-
- public static void CreateFolder(string FolderName)
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
-
- var FileMetaData = new Google.Apis.Drive.v3.Data.File();
- FileMetaData.Name = FolderName;
- FileMetaData.MimeType = "application/vnd.google-apps.folder";
-
- Google.Apis.Drive.v3.FilesResource.CreateRequest request;
-
- request = service.Files.Create(FileMetaData);
- request.Fields = "id";
- var file = request.Execute();
- Console.WriteLine("Folder ID: " + file.Id);
- }
-
-
- public static void CreateFolderInFolder(string folderId, string FolderName)
- {
-
- Google.Apis.Drive.v3.DriveService service = GetService();
-
- var FileMetaData = new Google.Apis.Drive.v3.Data.File()
- {
- Name = Path.GetFileName(FolderName),
- MimeType = "application/vnd.google-apps.folder",
- Parents = new List<string>
- {
- folderId
- }
- };
-
-
- Google.Apis.Drive.v3.FilesResource.CreateRequest request;
-
- request = service.Files.Create(FileMetaData);
- request.Fields = "id";
- var file = request.Execute();
- Console.WriteLine("Folder ID: " + file.Id);
-
- var file1 = request;
-
- }
-
-
- public static void FileUploadInFolder(string folderId, HttpPostedFileBase file)
- {
- if (file != null && file.ContentLength > 0)
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
-
- string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
- Path.GetFileName(file.FileName));
- file.SaveAs(path);
-
- var FileMetaData = new Google.Apis.Drive.v3.Data.File()
- {
- Name = Path.GetFileName(file.FileName),
- MimeType = MimeMapping.GetMimeMapping(path),
- Parents = new List<string>
- {
- folderId
- }
- };
-
- Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
- using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
- {
- request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
- request.Fields = "id";
- request.Upload();
- }
- var file1 = request.ResponseBody;
- }
- }
-
-
-
- public static bool CheckFolder(string FolderName)
- {
- bool IsExist = false;
-
- Google.Apis.Drive.v3.DriveService service = GetService();
-
-
- Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();
- FileListRequest.Fields = "nextPageToken, files(*)";
-
-
- IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
- List<GoogleDriveFile> FileList = new List<GoogleDriveFile>();
-
-
-
- files = files.Where(x => x.MimeType == "application/vnd.google-apps.folder" && x.Name== FolderName).ToList();
-
- if (files.Count > 0)
- {
- IsExist = false;
- }
- return IsExist;
- }
-
-
- public static List<GoogleDriveFile> GetDriveFolders()
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
- List<GoogleDriveFile> FolderList = new List<GoogleDriveFile>();
-
- Google.Apis.Drive.v3.FilesResource.ListRequest request = service.Files.List();
- request.Q = "mimeType='application/vnd.google-apps.folder'";
- request.Fields = "files(id, name)";
-
- Google.Apis.Drive.v3.Data.FileList result = request.Execute();
- foreach (var file in result.Files)
- {
- GoogleDriveFile File = new GoogleDriveFile
- {
- Id = file.Id,
- Name = file.Name,
- Size = file.Size,
- Version = file.Version,
- CreatedTime = file.CreatedTime
- };
- FolderList.Add(File);
- }
- return FolderList;
- }
-
- public static string MoveFiles(String fileId, String folderId)
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
-
-
- Google.Apis.Drive.v3.FilesResource.GetRequest getRequest = service.Files.Get(fileId);
- getRequest.Fields = "parents";
- Google.Apis.Drive.v3.Data.File file = getRequest.Execute();
- string previousParents = String.Join(",", file.Parents);
-
-
- Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId);
- updateRequest.Fields = "id, parents";
- updateRequest.AddParents = folderId;
- updateRequest.RemoveParents = previousParents;
-
- file = updateRequest.Execute();
- if (file != null)
- {
- return "Success";
- }
- else
- {
- return "Fail";
- }
- }
- public static string CopyFiles(String fileId, String folderId)
- {
- Google.Apis.Drive.v3.DriveService service = GetService();
-
-
- Google.Apis.Drive.v3.FilesResource.GetRequest getRequest = service.Files.Get(fileId);
- getRequest.Fields = "parents";
- Google.Apis.Drive.v3.Data.File file = getRequest.Execute();
-
-
- Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId);
- updateRequest.Fields = "id, parents";
- updateRequest.AddParents = folderId;
-
- file = updateRequest.Execute();
- if (file != null)
- {
- return "Success";
- }
- else
- {
- return "Fail";
- }
- }
-
- private static void RenameFile(String fileId, String newTitle)
- {
- try
- {
- Google.Apis.Drive.v2.DriveService service = GetService_v2();
-
- Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File();
- file.Title = newTitle;
-
-
- Google.Apis.Drive.v2.FilesResource.PatchRequest request = service.Files.Patch(file, fileId);
- Google.Apis.Drive.v2.Data.File updatedFile = request.Execute();
-
-
- }
- catch (Exception e)
- {
- Console.WriteLine("An error occurred: " + e.Message);
-
- }
- }
Step 14
Call the above method from controller.
- using DriveApi.Models;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace DriveApi.Controllers
- {
- public class HomeController : Controller
- {
- [HttpGet]
- public ActionResult GetGoogleDriveFiles()
- {
- return View(GoogleDriveFilesRepository.GetDriveFiles());
- }
-
- [HttpGet]
- public ActionResult GetGoogleDriveFiles1()
- {
- return View(GoogleDriveFilesRepository.GetDriveFiles());
- }
-
-
- [HttpGet]
- public ActionResult GetGoogleDriveFiles2()
- {
- return View(GoogleDriveFilesRepository.GetDriveFiles());
- }
-
- [HttpPost]
- public ActionResult DeleteFile(GoogleDriveFile file)
- {
- GoogleDriveFilesRepository.DeleteFile(file);
- return RedirectToAction("GetGoogleDriveFiles");
- }
-
- [HttpPost]
- public ActionResult UploadFile(HttpPostedFileBase file)
- {
- GoogleDriveFilesRepository.FileUpload(file);
- return RedirectToAction("GetGoogleDriveFiles");
- }
-
- public void DownloadFile(string id)
- {
- string FilePath = GoogleDriveFilesRepository.DownloadGoogleFile(id);
-
- Response.ContentType = "application/zip";
- Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(FilePath));
- Response.WriteFile(System.Web.HttpContext.Current.Server.MapPath("~/GoogleDriveFiles/" + Path.GetFileName(FilePath)));
- Response.End();
- Response.Flush();
- }
-
-
- [HttpGet]
- public ActionResult GetContainsInFolder(string folderId)
- {
- return View(GoogleDriveFilesRepository.GetContainsInFolder(folderId));
- }
-
- [HttpPost]
- public ActionResult CreateFolder(String FolderName)
- {
- GoogleDriveFilesRepository.CreateFolder(FolderName);
- return RedirectToAction("GetGoogleDriveFiles1");
- }
-
-
- [HttpPost]
- public ActionResult FileUploadInFolder(GoogleDriveFile FolderId, HttpPostedFileBase file)
- {
- GoogleDriveFilesRepository.FileUploadInFolder(FolderId.Id, file);
- return RedirectToAction("GetGoogleDriveFiles1");
- }
-
- [HttpGet]
- public JsonResult FolderLists()
- {
- List<GoogleDriveFile> AllFolders = GoogleDriveFilesRepository.GetDriveFolders();
- List<DDLOptions> obj = new List<DDLOptions>();
-
- foreach (GoogleDriveFile EachFolder in AllFolders)
- {
- obj.Add(new DDLOptions { Id = EachFolder.Id, Name = EachFolder.Name });
- }
- return Json(obj, JsonRequestBehavior.AllowGet);
- }
-
- public string MoveFiles(String fileId, String folderId)
- {
- string Result = GoogleDriveFilesRepository.MoveFiles(fileId, folderId);
- return Result;
- }
-
- public string CopyFiles(String fileId, String folderId)
- {
- string Result = GoogleDriveFilesRepository.CopyFiles(fileId, folderId);
- return Result;
- }
-
- public JsonResult Render_GetGoogleDriveFilesView()
- {
- Dictionary<string, object> jsonResult = new Dictionary<string, object>();
- var result = GoogleDriveFilesRepository.GetDriveFiles();
- jsonResult.Add("Html", RenderRazorViewToString("~/Views/Home/GetGoogleDriveFiles.cshtml", result));
- return Json(jsonResult, JsonRequestBehavior.AllowGet);
- }
-
- public string RenderRazorViewToString(string viewName, object model)
- {
- if (model != null)
- {
- ViewData.Model = model;
-
- }
- using (var sw = new StringWriter())
- {
- var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
- var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
- viewResult.View.Render(viewContext, sw);
- viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
- return sw.GetStringBuilder().ToString();
- }
- }
- }
- }
Step 15
Copy the below code and paste into your View code.
You can download the source code from
here