Amazon Ad

Friday 3 January 2020

How to upload download files from google drive using API v3 in asp.net c#

Below is the code to upload and download files using Google drive API v3 in asp.net c#. Please check the official page for your reference,

the link is https://developers.google.com/drive/api/v3/quickstart/dotnet. Before you start you must enable Google drive api access for your account. The mentioned link has all the details regarding the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Services;
using System.Web.Script.Services;
using System.Security.Cryptography.X509Certificates;

namespace GoogleDriveAPIWorking
{
    public partial class _Default : Page
    {

        //Reference from https://developers.google.com/drive/api/v3/quickstart/dotnet

        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        //, DriveService.Scope.DriveFile
        static string[] Scopes = { DriveService.Scope.Drive,
                          DriveService.Scope.DriveAppdata,
                          DriveService.Scope.DriveFile,
                          DriveService.Scope.DriveMetadataReadonly,
                          DriveService.Scope.DriveReadonly,
                          DriveService.Scope.DriveScripts };
        static string ApplicationName = "Testing Google Drive API";
        static DriveService service;

        private void initGService()
        {
            try
            {
                UserCredential credential;
                using (var stream = new FileStream(Server.MapPath("~/credentials.json"), FileMode.Open, FileAccess.Read))
                {
                    // The file token.json stores the user's access and refresh tokens, and is created
                    // automatically when the authorization flow completes for the first time.
                    string credPath = Server.MapPath("token.json");

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                         GoogleClientSecrets.Load(stream).Secrets,
                         Scopes,
                         "user",
                         CancellationToken.None,
                         new FileDataStore(credPath, true)).Result;

                    string s = "Credential file saved to: " + credPath;

                }

                // Create Drive API service.
                service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
            }
            catch (Exception ex)
            {

            }

        }

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!Page.IsPostBack)
            {

                initGService();
            }
            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name, webContentLink)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            //Console.WriteLine("Files:");
            //fileList.InnerHtml = "Your Files:<br/>";
            if (files != null && files.Count > 0)
            {
                int i = 1;
                foreach (var file in files)
                {
                    //fileList.InnerHtml += "<div style='text-decoration:underline;font-color:blue' onclick='downloadfile(\"" + file.Id + "\");return

false;'>" + file.Name + "</a><br/>";
                    //Console.WriteLine("{0} ({1})", file.Name, file.Id);

                    LinkButton lb = new LinkButton();
                    lb.ID = "id" + i;
                    lb.Text = file.Name;
                    lb.CommandArgument = file.Id + "|" + file.WebContentLink;
                    lb.Command += new CommandEventHandler(DownloadFile);
                    Panel1.Controls.Add(lb);
                    Panel1.Controls.Add(new LiteralControl("<br />"));
                    i++;
                }
            }
            else
            {
                fileList.InnerHtml = "No files found.";
            }
            //Console.Read();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {


            byte[] by = fu.FileBytes;
            string filename = fu.FileName;
            string contentType = fu.PostedFile.ContentType;

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = filename
            };

            FilesResource.CreateMediaUpload request;
            //using (var stream = new System.IO.FileStream(Server.MapPath("files") + "/photo.jpg", System.IO.FileMode.Open))
            using (var stream = fu.FileContent)
            {
                request = service.Files.Create(fileMetadata, stream, contentType);
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;
            fileList.InnerHtml = "<br/><br/>" + "File ID: " + file.Id;

            //UploadFileToDrive(Server.MapPath("files") + "/photo.jpg");
            //Console.WriteLine("File ID: " + file.Id)
        }


        public void DownloadFile(object sender, EventArgs e)
        {

            LinkButton btn = (LinkButton)(sender);
            string[] arr = btn.CommandArgument.Split('|');
            string fileId = arr[0];
            string DownloadUrl = arr[1];

            string status = "";
            try
            {
                //create a folder "Downloaded" in your project, before running this code
                string saveTo = HttpContext.Current.Server.MapPath("Downloaded");
                var stream = new System.IO.MemoryStream();
                var request = service.Files.Get(fileId);

                Google.Apis.Drive.v3.Data.File file = request.Execute();
                string fname = file.Name;
                string fext = file.FileExtension;


                // Add a handler which will be notified on progress changes.
                // It will notify on each chunk download and when the
                // download is completed or failed.
                request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                        case Google.Apis.Download.DownloadStatus.Downloading:
                            {
                                downloadstatus.InnerHtml += "<br/>Downloaded : " + (progress.BytesDownloaded.ToString());
                                status = "Downloaded : " + (progress.BytesDownloaded.ToString());
                                break;
                            }
                        case Google.Apis.Download.DownloadStatus.Completed:
                            {
                                downloadstatus.InnerHtml += "<br/>Download complete.";
                                status = "Success";
                                SaveStream(stream, saveTo + "//" + fname);
                                downloadstatus.InnerHtml += "File Saved to location " + saveTo;
                                break;
                            }
                        case Google.Apis.Download.DownloadStatus.Failed:
                            {
                                downloadstatus.InnerHtml = "<br/>(Download failed.";
                                status = "Failed";
                                break;
                            }
                    }
                };
                request.Download(stream);

            }
            catch (Exception ex)
            {
                status = ex.ToString();
            }
        }

        //Save file from stream to local location
        private static void SaveStream(System.IO.MemoryStream stream, string saveTo)
        {
            using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                stream.WriteTo(file);
            }
        }
    }
}

1 comment:

Anonymous said...

Asp.Net Programming And Solutions: How To Upload Files From Google Drive Using Api V3 In Asp.Net C >>>>> Download Now

>>>>> Download Full

Asp.Net Programming And Solutions: How To Upload Files From Google Drive Using Api V3 In Asp.Net C >>>>> Download LINK

>>>>> Download Now

Asp.Net Programming And Solutions: How To Upload Files From Google Drive Using Api V3 In Asp.Net C >>>>> Download Full

>>>>> Download LINK ws

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...