Google Drive API Integration And Use Of Functions

In this article, we learn how to integrate Google Drive API in MVC Projects and use the function for uploading files, creating folders, uploading files in folder,s moving files, renaming files or folders, creating a folder within another folder, getting all files, getting files from a specific folder, and deleting files

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.
 
Google Drive API Integration And Use Of Functions
 
Step 3
 
Create a new project by clicking on the "Continue" button.
 
Google Drive API Integration And Use Of Functions
 
Step 4
 
Click on the "Cancel" button.
 
Google Drive API Integration And Use Of Functions
 
Step 5
 
Go to "OAuth consent screen".
 
Google Drive API Integration And Use Of Functions
 
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.
 
Google Drive API Integration And Use Of Functions
 
Step 7
 
Go to the Credentials >> OAuth client ID.
 
Google Drive API Integration And Use Of Functions
 
Step 8
 
Select the web application and click on the "Create" button.
 
Google Drive API Integration And Use Of Functions
 
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).
 
Google Drive API Integration And Use Of Functions
 
This file contains clients information.
 
These are,
  1. client id, 
  2. client secret id, 
  3. project_id
  4. auth_uri,
  5. token_uri
  6. 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.
 
Google Drive API Integration And Use Of Functions
 
Step 11 - Install the NuGet package
 
Opening the NuGet Package Manager Console, select the package source and run these following two commands.
  1. Install-Package Google.Apis.Drive.v3
  2. 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.
 
Google Drive API Integration And Use Of Functions
 
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.
  1. public static void CreateFolderOnDrive(string Folder_Name)    
  2.         {    
  3.             Google.Apis.Drive.v3.DriveService service = GetService_v3();    
  4.     
  5.             Google.Apis.Drive.v3.Data.File FileMetaData = new     
  6.             Google.Apis.Drive.v3.Data.File();    
  7.             FileMetaData.Name = Folder_Name;    
  8.             FileMetaData.MimeType = "application/vnd.google-apps.folder";    
  9.     
  10.             Google.Apis.Drive.v3.FilesResource.CreateRequest request;    
  11.     
  12.             request = service.Files.Create(FileMetaData);    
  13.             request.Fields = "id";    
  14.             var file = request.Execute();    
  15.         }    
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.
  1. public static void FileUploadInFolder(string folderId, HttpPostedFileBase file)    
  2.         {    
  3.             if (file != null && file.ContentLength > 0)    
  4.             {    
  5.                 Google.Apis.Drive.v3.DriveService service = GetService_v3();    
  6.     
  7.                 string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),    
  8.                 Path.GetFileName(file.FileName));    
  9.                 file.SaveAs(path);    
  10.     
  11.                 var FileMetaData = new Google.Apis.Drive.v3.Data.File()    
  12.                 {    
  13.                     Name = Path.GetFileName(file.FileName),    
  14.                     MimeType = MimeMapping.GetMimeMapping(path),    
  15.                     Parents = new List<string>    
  16.                     {    
  17.                         folderId    
  18.                     }    
  19.                 };    
  20.                 Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;    
  21.                 using (var stream = new System.IO.FileStream(path,     
  22.                 System.IO.FileMode.Open))    
  23.                 {    
  24.                     request = service.Files.Create(FileMetaData, stream,     
  25.                     FileMetaData.MimeType);    
  26.                     request.Fields = "id";    
  27.                     request.Upload();    
  28.                 }    
  29.                 var file1 = request.ResponseBody;    
  30.             }    
  31.         }    
After creating .cs file, add all the below references for Google API to use.
  1. using Google.Apis.Auth.OAuth2;    
  2. using Google.Apis.Download;    
  3. using Google.Apis.Drive.v2;    
  4. using Google.Apis.Drive.v3;    
  5. using Google.Apis.Services;    
  6. using Google.Apis.Util.Store;    
  7. using System;    
  8. using System.Collections.Generic;    
  9. using System.IO;    
  10. using System.Linq;    
  11. using System.Threading;    
  12. using System.Web;    
  13. public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.Drive};    
  14.     
  15.        //create Drive API service.    
  16.        public static Google.Apis.Drive.v3.DriveService GetService()    
  17.        {    
  18.            //get Credentials from client_secret.json file     
  19.            UserCredential credential;    
  20.            var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/");    
  21.     
  22.            using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))    
  23.            {    
  24.                String FolderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/"); ;    
  25.                String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");    
  26.     
  27.                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(    
  28.                    GoogleClientSecrets.Load(stream).Secrets,    
  29.                    Scopes,    
  30.                    "user",    
  31.                    CancellationToken.None,    
  32.                    new FileDataStore(FilePath, true)).Result;    
  33.            }    
  34.     
  35.            //create Drive API service.    
  36.            Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()    
  37.            {    
  38.                HttpClientInitializer = credential,    
  39.                ApplicationName = "GoogleDriveRestAPI-v3",    
  40.            });    
  41.            return service;    
  42.        }    
  43.     
  44.        public static Google.Apis.Drive.v2.DriveService GetService_v2()    
  45.        {    
  46.            UserCredential credential;    
  47.            var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/");    
  48.     
  49.            using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))    
  50.            {    
  51.                 
  52.                String FilePath = Path.Combine(CSPath, "DriveServiceCredentials.json");    
  53.     
  54.                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(    
  55.                    GoogleClientSecrets.Load(stream).Secrets,    
  56.                    Scopes,    
  57.                    "user",    
  58.                    CancellationToken.None,    
  59.                    new FileDataStore(FilePath, true)).Result;    
  60.            }    
  61.     
  62.            //Create Drive API service.    
  63.            Google.Apis.Drive.v2.DriveService service = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer()    
  64.            {    
  65.                HttpClientInitializer = credential,    
  66.                ApplicationName = "GoogleDriveRestAPI-v2",    
  67.            });    
  68.            return service;    
  69.        }    
  70.     
  71.        //get all files from Google Drive.    
  72.        public static List<GoogleDriveFile> GetDriveFiles()    
  73.        {    
  74.            Google.Apis.Drive.v3.DriveService service = GetService();    
  75.     
  76.            // Define parameters of request.    
  77.            Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();    
  78.           // for getting folders only.    
  79.            //FileListRequest.Q = "mimeType='application/vnd.google-apps.folder'";    
  80.            FileListRequest.Fields = "nextPageToken, files(*)";    
  81.     
  82.            // List files.    
  83.            IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;    
  84.            List<GoogleDriveFile> FileList = new List<GoogleDriveFile>();    
  85.     
  86.     
  87.            // For getting only folders    
  88.           // files = files.Where(x => x.MimeType == "application/vnd.google-apps.folder").ToList();    
  89.     
  90.     
  91.            if (files != null && files.Count > 0)    
  92.            {    
  93.                foreach (var file in files)    
  94.                {    
  95.                    GoogleDriveFile File = new GoogleDriveFile    
  96.                    {    
  97.                        Id = file.Id,    
  98.                        Name = file.Name,    
  99.                        Size = file.Size,    
  100.                        Version = file.Version,    
  101.                        CreatedTime = file.CreatedTime,    
  102.                        Parents = file.Parents,    
  103.                        MimeType = file.MimeType    
  104.                    };    
  105.                    FileList.Add(File);    
  106.                }    
  107.            }    
  108.            return FileList;    
  109.        }    
  110.     
  111.        //file Upload to the Google Drive root folder.    
  112.        public static void FileUpload(HttpPostedFileBase file)    
  113.        {    
  114.            if (file != null && file.ContentLength > 0)    
  115.            {    
  116.                Google.Apis.Drive.v3.DriveService service = GetService();    
  117.     
  118.                string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),    
  119.                Path.GetFileName(file.FileName));    
  120.                file.SaveAs(path);    
  121.     
  122.                var FileMetaData = new Google.Apis.Drive.v3.Data.File();    
  123.                FileMetaData.Name = Path.GetFileName(file.FileName);    
  124.                FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);    
  125.     
  126.                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;    
  127.     
  128.                using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))    
  129.                {    
  130.                    request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);    
  131.                    request.Fields = "id";    
  132.                    request.Upload();    
  133.                }    
  134.     
  135.     
  136.                // Create Folder in Drive    
  137.                    
  138.                    
  139.            }    
  140.        }    
  141.     
  142.        //Download file from Google Drive by fileId.    
  143.        public static string DownloadGoogleFile(string fileId)    
  144.        {    
  145.            Google.Apis.Drive.v3.DriveService service = GetService();    
  146.     
  147.            string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");    
  148.            Google.Apis.Drive.v3.FilesResource.GetRequest request = service.Files.Get(fileId);    
  149.     
  150.            string FileName = request.Execute().Name;    
  151.            string FilePath = System.IO.Path.Combine(FolderPath, FileName);    
  152.     
  153.            MemoryStream stream1 = new MemoryStream();    
  154.     
  155.            // Add a handler which will be notified on progress changes.    
  156.            // It will notify on each chunk download and when the    
  157.            // download is completed or failed.    
  158.            request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>    
  159.            {    
  160.                switch (progress.Status)    
  161.                {    
  162.                    case DownloadStatus.Downloading:    
  163.                        {    
  164.                            Console.WriteLine(progress.BytesDownloaded);    
  165.                            break;    
  166.                        }    
  167.                    case DownloadStatus.Completed:    
  168.                        {    
  169.                            Console.WriteLine("Download complete.");    
  170.                            SaveStream(stream1, FilePath);    
  171.                            break;    
  172.                        }    
  173.                    case DownloadStatus.Failed:    
  174.                        {    
  175.                            Console.WriteLine("Download failed.");    
  176.                            break;    
  177.                        }    
  178.                }    
  179.            };    
  180.            request.Download(stream1);    
  181.            return FilePath;    
  182.        }    
  183.     
  184.        // file save to server path    
  185.        private static void SaveStream(MemoryStream stream, string FilePath)    
  186.        {    
  187.            using (System.IO.FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))    
  188.            {    
  189.                stream.WriteTo(file);    
  190.            }    
  191.        }    
  192.     
  193.        //Delete file from the Google drive    
  194.        public static void DeleteFile(GoogleDriveFile files)    
  195.        {    
  196.            Google.Apis.Drive.v3.DriveService service = GetService();    
  197.            try    
  198.            {    
  199.                // Initial validation.    
  200.                if (service == null)    
  201.                    throw new ArgumentNullException("service");    
  202.     
  203.                if (files == null)    
  204.                    throw new ArgumentNullException(files.Id);    
  205.     
  206.                // Make the request.    
  207.                service.Files.Delete(files.Id).Execute();    
  208.            }    
  209.            catch (Exception ex)    
  210.            {    
  211.                throw new Exception("Request Files.Delete failed.", ex);    
  212.            }    
  213.        }    
  214.            
  215.        public static List<GoogleDriveFile> GetContainsInFolder(String folderId)    
  216.        {    
  217.            List<string> ChildList = new List<string>();    
  218.            Google.Apis.Drive.v2.DriveService ServiceV2 = GetService_v2();    
  219.            ChildrenResource.ListRequest ChildrenIDsRequest = ServiceV2.Children.List(folderId);    
  220.     
  221.            // for getting only folders    
  222.            //ChildrenIDsRequest.Q = "mimeType='application/vnd.google-apps.folder'";    
  223.            do    
  224.            {    
  225.                var children = ChildrenIDsRequest.Execute();    
  226.     
  227.                if (children.Items != null && children.Items.Count > 0)    
  228.                {    
  229.                    foreach (var file in children.Items)    
  230.                    {    
  231.                        ChildList.Add(file.Id);    
  232.                    }    
  233.                }    
  234.                ChildrenIDsRequest.PageToken = children.NextPageToken;    
  235.     
  236.            } while (!String.IsNullOrEmpty(ChildrenIDsRequest.PageToken));    
  237.     
  238.            //Get All File List    
  239.            List<GoogleDriveFile> AllFileList = GetDriveFiles();    
  240.            List<GoogleDriveFile> Filter_FileList = new List<GoogleDriveFile>();    
  241.     
  242.            foreach (string Id in ChildList)    
  243.            {    
  244.                Filter_FileList.Add(AllFileList.Where(x => x.Id == Id).FirstOrDefault());    
  245.            }    
  246.            return Filter_FileList;    
  247.        }    
  248.     
  249.        // Create Folder in root    
  250.        public static void CreateFolder(string FolderName)    
  251.        {    
  252.            Google.Apis.Drive.v3.DriveService service = GetService();    
  253.     
  254.            var FileMetaData = new Google.Apis.Drive.v3.Data.File();    
  255.            FileMetaData.Name = FolderName;    
  256.            FileMetaData.MimeType = "application/vnd.google-apps.folder";    
  257.     
  258.            Google.Apis.Drive.v3.FilesResource.CreateRequest request;    
  259.     
  260.            request = service.Files.Create(FileMetaData);    
  261.            request.Fields = "id";    
  262.            var file = request.Execute();    
  263.            Console.WriteLine("Folder ID: " + file.Id);    
  264.        }    
  265.     
  266.        // Create Folder in existing folder    
  267.        public static void CreateFolderInFolder(string folderId, string FolderName)    
  268.        {    
  269.     
  270.            Google.Apis.Drive.v3.DriveService service = GetService();    
  271.     
  272.            var FileMetaData = new Google.Apis.Drive.v3.Data.File()    
  273.            {    
  274.                Name = Path.GetFileName(FolderName),    
  275.                MimeType = "application/vnd.google-apps.folder",    
  276.                Parents = new List<string>    
  277.                    {    
  278.                        folderId    
  279.                    }    
  280.            };    
  281.     
  282.                
  283.            Google.Apis.Drive.v3.FilesResource.CreateRequest request;    
  284.     
  285.            request = service.Files.Create(FileMetaData);    
  286.            request.Fields = "id";    
  287.            var file = request.Execute();    
  288.            Console.WriteLine("Folder ID: " + file.Id);    
  289.     
  290.            var file1 = request;    
  291.     
  292.        }    
  293.     
  294.        // File upload in existing folder    
  295.        public static void FileUploadInFolder(string folderId, HttpPostedFileBase file)    
  296.        {    
  297.            if (file != null && file.ContentLength > 0)    
  298.            {    
  299.                Google.Apis.Drive.v3.DriveService service = GetService();    
  300.     
  301.                string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),    
  302.                Path.GetFileName(file.FileName));    
  303.                file.SaveAs(path);    
  304.     
  305.                var FileMetaData = new Google.Apis.Drive.v3.Data.File()    
  306.                {    
  307.                    Name = Path.GetFileName(file.FileName),    
  308.                    MimeType = MimeMapping.GetMimeMapping(path),    
  309.                    Parents = new List<string>    
  310.                    {    
  311.                        folderId    
  312.                    }    
  313.                };    
  314.     
  315.                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;    
  316.                using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))    
  317.                {    
  318.                    request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);    
  319.                    request.Fields = "id";    
  320.                    request.Upload();    
  321.                }    
  322.                var file1 = request.ResponseBody;    
  323.            }    
  324.        }    
  325.            
  326.     
  327.        // check Folder name exist or note in root    
  328.        public static bool CheckFolder(string FolderName)    
  329.        {    
  330.            bool IsExist = false;    
  331.                
  332.            Google.Apis.Drive.v3.DriveService service = GetService();    
  333.                
  334.            // Define the parameters of the request.    
  335.            Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();    
  336.            FileListRequest.Fields = "nextPageToken, files(*)";    
  337.     
  338.            // List files.    
  339.            IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;    
  340.            List<GoogleDriveFile> FileList = new List<GoogleDriveFile>();    
  341.     
  342.     
  343.            //For getting only folders    
  344.             files = files.Where(x => x.MimeType == "application/vnd.google-apps.folder" && x.Name== FolderName).ToList();    
  345.                
  346.            if (files.Count > 0)    
  347.            {    
  348.                IsExist = false;        
  349.            }    
  350.            return IsExist;    
  351.        }    
  352.     
  353.     
  354.        public static List<GoogleDriveFile> GetDriveFolders()    
  355.        {    
  356.            Google.Apis.Drive.v3.DriveService service = GetService();    
  357.            List<GoogleDriveFile> FolderList = new List<GoogleDriveFile>();    
  358.     
  359.            Google.Apis.Drive.v3.FilesResource.ListRequest request = service.Files.List();    
  360.            request.Q = "mimeType='application/vnd.google-apps.folder'";    
  361.            request.Fields = "files(id, name)";    
  362.     
  363.            Google.Apis.Drive.v3.Data.FileList result = request.Execute();    
  364.            foreach (var file in result.Files)    
  365.            {    
  366.                GoogleDriveFile File = new GoogleDriveFile    
  367.                {    
  368.                    Id = file.Id,    
  369.                    Name = file.Name,    
  370.                    Size = file.Size,    
  371.                    Version = file.Version,    
  372.                    CreatedTime = file.CreatedTime    
  373.                };    
  374.                FolderList.Add(File);    
  375.            }    
  376.            return FolderList;    
  377.        }    
  378.     
  379.        public static string MoveFiles(String fileId, String folderId)    
  380.        {    
  381.            Google.Apis.Drive.v3.DriveService service = GetService();    
  382.     
  383.            // Retrieve the existing parents to remove    
  384.            Google.Apis.Drive.v3.FilesResource.GetRequest getRequest = service.Files.Get(fileId);    
  385.            getRequest.Fields = "parents";    
  386.            Google.Apis.Drive.v3.Data.File file = getRequest.Execute();    
  387.            string previousParents = String.Join(",", file.Parents);    
  388.     
  389.            // Move the file to the new folder    
  390.            Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId);    
  391.            updateRequest.Fields = "id, parents";    
  392.            updateRequest.AddParents = folderId;    
  393.            updateRequest.RemoveParents = previousParents;    
  394.     
  395.            file = updateRequest.Execute();    
  396.            if (file != null)    
  397.            {    
  398.                return "Success";    
  399.            }    
  400.            else    
  401.            {    
  402.                return "Fail";    
  403.            }    
  404.        }    
  405.        public static string CopyFiles(String fileId, String folderId)    
  406.        {    
  407.            Google.Apis.Drive.v3.DriveService service = GetService();    
  408.     
  409.            // Retrieve the existing parents to remove    
  410.            Google.Apis.Drive.v3.FilesResource.GetRequest getRequest = service.Files.Get(fileId);    
  411.            getRequest.Fields = "parents";    
  412.            Google.Apis.Drive.v3.Data.File file = getRequest.Execute();    
  413.     
  414.            // Copy the file to the new folder    
  415.            Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId);    
  416.            updateRequest.Fields = "id, parents";    
  417.            updateRequest.AddParents = folderId;    
  418.            //updateRequest.RemoveParents = previousParents;    
  419.            file = updateRequest.Execute();    
  420.            if (file != null)    
  421.            {    
  422.                return "Success";    
  423.            }    
  424.            else    
  425.            {    
  426.                return "Fail";    
  427.            }    
  428.        }    
  429.     
  430.        private static void RenameFile(String fileId, String newTitle)    
  431.        {    
  432.            try    
  433.            {    
  434.                Google.Apis.Drive.v2.DriveService service = GetService_v2();    
  435.     
  436.                Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File();    
  437.                file.Title = newTitle;    
  438.     
  439.                // Rename the file.    
  440.                Google.Apis.Drive.v2.FilesResource.PatchRequest request = service.Files.Patch(file, fileId);    
  441.                Google.Apis.Drive.v2.Data.File updatedFile = request.Execute();    
  442.     
  443.                //return updatedFile;    
  444.            }    
  445.            catch (Exception e)    
  446.            {    
  447.                Console.WriteLine("An error occurred: " + e.Message);    
  448.                //return null;    
  449.            }    
  450.        }    
Step 14
 
Call the above method from controller.
  1. using DriveApi.Models;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.IO;    
  5. using System.Linq;    
  6. using System.Web;    
  7. using System.Web.Mvc;    
  8.     
  9. namespace DriveApi.Controllers    
  10. {    
  11.     public class HomeController : Controller    
  12.     {    
  13.         [HttpGet]    
  14.         public ActionResult GetGoogleDriveFiles()    
  15.         {    
  16.             return View(GoogleDriveFilesRepository.GetDriveFiles());    
  17.         }    
  18.             
  19.         [HttpGet]    
  20.         public ActionResult GetGoogleDriveFiles1()    
  21.         {    
  22.             return View(GoogleDriveFilesRepository.GetDriveFiles());    
  23.         }    
  24.     
  25.     
  26.         [HttpGet]    
  27.         public ActionResult GetGoogleDriveFiles2()    
  28.         {    
  29.             return View(GoogleDriveFilesRepository.GetDriveFiles());    
  30.         }    
  31.     
  32.         [HttpPost]    
  33.         public ActionResult DeleteFile(GoogleDriveFile file)    
  34.         {    
  35.             GoogleDriveFilesRepository.DeleteFile(file);    
  36.             return RedirectToAction("GetGoogleDriveFiles");    
  37.         }    
  38.     
  39.         [HttpPost]    
  40.         public ActionResult UploadFile(HttpPostedFileBase file)    
  41.         {    
  42.             GoogleDriveFilesRepository.FileUpload(file);    
  43.             return RedirectToAction("GetGoogleDriveFiles");    
  44.         }    
  45.     
  46.         public void DownloadFile(string id)    
  47.         {    
  48.             string FilePath = GoogleDriveFilesRepository.DownloadGoogleFile(id);    
  49.                     
  50.             Response.ContentType = "application/zip";    
  51.             Response.AddHeader("Content-Disposition""attachment; filename=" + Path.GetFileName(FilePath));    
  52.             Response.WriteFile(System.Web.HttpContext.Current.Server.MapPath("~/GoogleDriveFiles/" + Path.GetFileName(FilePath)));    
  53.             Response.End();    
  54.             Response.Flush();    
  55.         }    
  56.             
  57.     
  58.         [HttpGet]    
  59.         public ActionResult GetContainsInFolder(string folderId)    
  60.         {    
  61.             return View(GoogleDriveFilesRepository.GetContainsInFolder(folderId));    
  62.         }    
  63.     
  64.         [HttpPost]    
  65.         public ActionResult CreateFolder(String FolderName)    
  66.         {    
  67.             GoogleDriveFilesRepository.CreateFolder(FolderName);    
  68.             return RedirectToAction("GetGoogleDriveFiles1");    
  69.         }    
  70.     
  71.             
  72.         [HttpPost]    
  73.         public ActionResult FileUploadInFolder(GoogleDriveFile FolderId, HttpPostedFileBase file)    
  74.         {    
  75.             GoogleDriveFilesRepository.FileUploadInFolder(FolderId.Id, file);    
  76.             return RedirectToAction("GetGoogleDriveFiles1");    
  77.         }    
  78.             
  79.         [HttpGet]    
  80.         public JsonResult FolderLists()    
  81.         {    
  82.             List<GoogleDriveFile> AllFolders = GoogleDriveFilesRepository.GetDriveFolders();    
  83.             List<DDLOptions> obj = new List<DDLOptions>();    
  84.     
  85.             foreach (GoogleDriveFile EachFolder in AllFolders)    
  86.             {    
  87.                 obj.Add(new DDLOptions { Id = EachFolder.Id, Name = EachFolder.Name });    
  88.             }    
  89.             return Json(obj, JsonRequestBehavior.AllowGet);    
  90.         }    
  91.     
  92.         public string MoveFiles(String fileId, String folderId)    
  93.         {    
  94.             string Result = GoogleDriveFilesRepository.MoveFiles(fileId, folderId);    
  95.             return Result;    
  96.         }    
  97.     
  98.         public string CopyFiles(String fileId, String folderId)    
  99.         {    
  100.             string Result = GoogleDriveFilesRepository.CopyFiles(fileId, folderId);    
  101.             return Result;    
  102.         }    
  103.     
  104.         public JsonResult Render_GetGoogleDriveFilesView()    
  105.         {    
  106.             Dictionary<stringobject> jsonResult = new Dictionary<stringobject>();    
  107.             var result = GoogleDriveFilesRepository.GetDriveFiles();    
  108.             jsonResult.Add("Html", RenderRazorViewToString("~/Views/Home/GetGoogleDriveFiles.cshtml", result));    
  109.             return Json(jsonResult, JsonRequestBehavior.AllowGet);    
  110.         }    
  111.     
  112.         public string RenderRazorViewToString(string viewName, object model)    
  113.         {    
  114.             if (model != null)    
  115.             {    
  116.                 ViewData.Model = model;    
  117.     
  118.             }    
  119.             using (var sw = new StringWriter())    
  120.             {    
  121.                 var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);    
  122.                 var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);    
  123.                 viewResult.View.Render(viewContext, sw);    
  124.                 viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);    
  125.                 return sw.GetStringBuilder().ToString();    
  126.             }    
  127.         }       
  128.     }    
  129. }    
Step 15
 
Copy the below code and paste into your View code.
  1.     @model IEnumerable<DriveApi.Models.GoogleDriveFile>    
  2.     @{    
  3.         ViewBag.Title = "GetGoogleDriveFiles";    
  4.     }    
  5.         
  6.     <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>    
  7.         
  8.     <style type="text/css">    
  9.         #header {    
  10.             width: 100%;    
  11.             background-color: #CCCCCC;    
  12.             text-align: center;    
  13.         }    
  14.        
  15.         #layouttable {    
  16.             border: 0px;    
  17.             width: 100%;    
  18.             font-family: 'Segoe UI';    
  19.         }    
  20.        
  21.             #layouttable td.col1 {    
  22.                 width: 20%;    
  23.                 vertical-align: top;    
  24.             }    
  25.        
  26.             #layouttable td.col2 {    
  27.                 width: 60%;    
  28.                 vertical-align: top;    
  29.                 background-color: #E8E8E8;    
  30.             }    
  31.        
  32.             #layouttable td.col3 {    
  33.                 width: 20%;    
  34.                 vertical-align: top;    
  35.             }    
  36.     </style>    
  37.         
  38.     <center>    
  39.         
  40.         
  41.         @using (Html.BeginForm("UploadFile""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))    
  42.         {    
  43.             <div class="row" style="margin-top:10px;margin-bottom:10px;">    
  44.                 <div class="col-md-2"><label for="file">Upload file:</label></div>    
  45.         
  46.                 <div class="col-md-2">    
  47.                     <input type="file" name="file" id="file" />    
  48.                 </div>    
  49.                 <div class="col-md-2">     
  50.                     <input type="submit" class="btn btn-success" value="Upload" />    
  51.                 </div>    
  52.             </div>    
  53.         }    
  54.         
  55.         
  56.         <table class="table" border="1">    
  57.             <tr id="header">    
  58.                 <th>    
  59.                     <label>Created Date</label>    
  60.                 </th>    
  61.                 <th>    
  62.                     <label>Name</label>    
  63.                 </th>    
  64.                 <th>    
  65.                     <label>Type</label>    
  66.                 </th>    
  67.                 <th>    
  68.                     <label>Size</label>    
  69.                 </th>    
  70.         
  71.                 <th>    
  72.                     Action    
  73.                 </th>    
  74.             </tr>    
  75.         
  76.             @if (Model.Count() > 0)    
  77.             {    
  78.                 foreach (var item in Model)    
  79.                 {    
  80.                     <tr id="layouttable">    
  81.                         <td>    
  82.                             @string.Format("{0: dd/MM/yyyy}", Convert.ToDateTime(item.CreatedTime))    
  83.                         </td>    
  84.                         <td>    
  85.                             @item.Name    
  86.                         </td>    
  87.                         <td>    
  88.                             @item.MimeType    
  89.                         </td>    
  90.                         <td>    
  91.                             @{    
  92.                                 long? KiloByte = @item.Size / 1024;    
  93.                                 string NewSize = KiloByte + " KB";    
  94.                             }    
  95.                             @NewSize    
  96.                         </td>    
  97.         
  98.                         <td>    
  99.                             <a class="btn btn-primary" href="/Home/DownloadFile/@item.Id">Download</a>    
  100.                             @using (Html.BeginForm("DeleteFile""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))    
  101.                             {    
  102.                                 <input type="hidden" name=Id value="@item.Id">    
  103.                                 <input type="submit" class="DeleteFile btn btn-danger" value="Delete" style="align-content:center;margin-top:5px;" />    
  104.                             }    
  105.         
  106.                         </td>    
  107.                     </tr>    
  108.                  }    
  109.                }    
  110.               else    
  111.               {    
  112.                     <td colspan="6">No files found</td>    
  113.               }    
  114.         
  115.         </table>    
  116.         
  117.     </center>    
  118.         
  119.     <script>    
  120.         $(document).on('click''.DownloadFile'function (fileId) {    
  121.             var fileId = $(this).attr("data-key");    
  122.         window.location.href = '/Home/DownloadFile/' + fileId;    
  123.     });    
  124. </script>    
You can download the source code from here