private static bool getCredential(string clientSecretPath, string userName)
        {
            string savePath = Path.Combine(appDataSavePath, Path.GetFileName(clientSecretPath));

            if (System.IO.File.Exists(savePath))
            {
                try
                {
                    using (var stream = new FileStream(savePath, FileMode.Open, FileAccess.Read))
                    {
                        string credPath = Path.Combine(appDataSavePath, ".credentials");

                        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                            GoogleClientSecrets.Load(stream).Secrets,
                            Scopes,
                            "Drive-" + userName,
                            CancellationToken.None,
                            new FileDataStore(credPath, true)).Result;
                    }
                    return(true);
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Debug.WriteLine(exc.Message + " Get Credential Error");
                    Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                       Environment.NewLine + exc.Message + " Get Credential Error.\n");
                    return(false);
                }
            }
            else
            {
                System.IO.File.Copy(clientSecretPath, Path.Combine(appDataSavePath, Path.GetFileName(clientSecretPath)));
                return(getCredential(clientSecretPath, userName));
            }
        }
        public static string createFolderToDrive(string folderName, string parentId)
        {
            try
            {
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name     = folderName,
                    MimeType = "application/vnd.google-apps.folder",
                };
                if (parentId != null)
                {
                    fileMetadata.Parents = new List <string>
                    {
                        parentId
                    };
                }

                var request = driveService.Files.Create(fileMetadata);
                request.Fields = "id";
                var file = request.Execute();
                System.Diagnostics.Debug.WriteLine("{0} {1}", file.Name, file.Id);
                return(file.Id);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Create Folder to Drive Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Create Folder to Drive Error.\n");
                return(null);
            }
        }
        public static string compressFile(string path)
        {
            string zipPath = path.Split('.').First() + ".zip";

            try
            {
                using (ZipFile zip = new ZipFile(Encoding.UTF8))
                {
                    if (Path.HasExtension(path))
                    {
                        zip.AddFile(@path);
                    }
                    else
                    {
                        zip.AddDirectory(@path);
                    }
                    zip.Save(@zipPath);
                }
                return(@zipPath);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Compress IO.File Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Compress IO.File Error.\n");
                return(null);
            }
        }
Beispiel #4
0
 private void createLogFile()
 {
     if (!System.IO.File.Exists(errorLog))
     {
         Gtools.createFile(errorLog, DateTime.Now.ToString() + Environment.NewLine + "Error Log file Created\n" + Environment.NewLine);
     }
 }
Beispiel #5
0
        //private void downRun(string fileName, string fileID, string mimeType, string SelectedPath)
        //{
        //    try
        //    {
        //        GoogleDriveAPIV3.downloadFromDrive(fileName, fileID, SelectedPath, mimeType);
        //    }
        //    catch(Exception ex) { MessageBox.Show(ex.ToString()); }
        //}


        private void btnUpload_Click(object sender, EventArgs e)
        {
            string filePath, fileName;
            string parentID = (txtParentID.Text != string.Empty) ? txtParentID.Text : null;
            bool   result;

            if (chbUploadMultiple.Checked)
            {
                result = (MessageBox.Show("Do you want to upload only new/changed files on Google Drive ?",
                                          "Upload existing files?",
                                          MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes);
                try
                {
                    lbFilesToUpload.BeginUpdate();

                    for (int i = lbFilesToUpload.Items.Count - 1; i >= 0; i--)
                    {
                        // lbFilesToUpload.Items[i].c
                        filePath = (chbCompress.Checked) ? Gtools.compressFile(lbFilesToUpload.Items[i].ToString()) : lbFilesToUpload.Items[i].ToString();
                        System.Diagnostics.Debug.WriteLine(filePath);
                        fileName = (chbCompress.Checked) ? Path.GetFileName(lbFilesToUpload.Items[i].ToString().Split('.').First()) + ".zip" : Path.GetFileName(lbFilesToUpload.Items[i].ToString());
                        GoogleDriveAPIV3.uploadToDrive(filePath, fileName, parentID, result, this);


                        string newName = "DONE!  " + lbFilesToUpload.Items[i].ToString();

                        lbFilesToUpload.Items.RemoveAt(i);
                        lbFilesToUpload.Items.Insert(i, newName);
                        updateDataGridView();
                    }
                    lbFilesToUpload.EndUpdate();
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Debug.WriteLine(exc.Message);
                    lbFilesToUpload.EndUpdate();
                }
            }
            else
            {
                filePath = (chbCompress.Checked) ? Gtools.compressFile(txtFilePath.Text) : txtFilePath.Text;
                fileName = (chbCompress.Checked) ? txtFileName.Text.Split('.').First() + ".zip" : txtFileName.Text;
                if (GoogleDriveAPIV3.compareHash(Gtools.hashGenerator(filePath)))
                {
                    result = MessageBox.Show("The file : \"" + fileName +
                                             "\" \nAlready exists on Google Drive!! \nDo you want to uploaded anyway?",
                                             "File already exist on Google Drive",
                                             MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;


                    Task.Run(() => { GoogleDriveAPIV3.uploadToDrive(filePath, fileName, parentID, !result, this); updateDataGridView(); });
                }
                else
                {
                    Task.Run(() => { GoogleDriveAPIV3.uploadToDrive(filePath, fileName, parentID, false, this); updateDataGridView(); });
                }
            }
        }
Beispiel #6
0
 private void updateDataGridView(string name = null, string type = null)
 {
     dtCalendar             = null;
     dtCalendar             = Gtools.ToDataTable <GoogleCaledar>(GoogleCalendarAPIV3.listCalendar());
     dgvCalendar.DataSource = dtCalendar;
     //dgvCalendar.Rows.Clear();
     //foreach(GoogleCaledar item in GoogleCalendarAPIV3.listCalendar())
     //{
     //    dgvCalendar.Rows.Add(new string[] { item.})
     //}
 }
Beispiel #7
0
        private void updateDataGridView(string name = null, string type = null)
        {
            if (InvokeRequired)
            {
                Invoke(new Action <string, string>(updateDataGridView), new object[] { name, type });
                return;
            }

            dtDriveFiles = null;
            dtDriveFiles = Gtools.ToDataTable <GoogleDriveFile>(GoogleDriveAPIV3.listDriveFiles(name, type));
            dgvFilesFromDrive.DataSource = dtDriveFiles;
        }
 public static void removeFile(string fileID)
 {
     try
     {
         var request = driveService.Files.Delete(fileID);
         request.Execute();
     }
     catch (Exception exc)
     {
         System.Diagnostics.Debug.WriteLine(exc.Message + " Remove Drive File error");
         Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                            Environment.NewLine + exc.Message + " Remove Drive File Error.\n");
     }
 }
Beispiel #9
0
        private void button_browse_Click(object sender, EventArgs e)
        {
            DialogResult result = ofgFileToUpload.ShowDialog();

            switch (result)
            {
            case DialogResult.OK:
                txtFilePath.Text = ofgFileToUpload.FileName;
                txtMd5.Text      = Gtools.hashGenerator(ofgFileToUpload.FileName);
                break;

            default:
                break;
            }
        }
Beispiel #10
0
        private void saveFileLIst(string saveFile)
        {
            try
            {
                string contentsToWriteToFile = JsonConvert.SerializeObject(IOFileList.ToArray(), Newtonsoft.Json.Formatting.Indented);

                System.IO.File.WriteAllText(saveFile, contentsToWriteToFile);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Save User Error.\n");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Save User Error.\n");
            }
        }
Beispiel #11
0
        private static void startWithArgs(string[] args)
        {
            string uploadFilePath, filename, backupName, parentID;
            int    user, compressing = 0, onlyNew = 0;

            try
            {
                if (loadUsers() && args.Length > 5)
                {
                    loadFileList(args[0]);
                    backupName = args[1];
                    parentID   = (args[2] != "0") ? args[2] : null;
                    int.TryParse(args[3], out user);
                    int.TryParse(args[4], out onlyNew);
                    int.TryParse(args[5], out compressing);


                    if (GoogleDriveAPIV3.GoogleDriveConnection(
                            UserList[user].clientSecretPath,
                            UserList[user].userName))
                    {
                        parentID = GoogleDriveAPIV3.createFolderToDrive(
                            Gtools.getTimeStamp() + "_" + backupName,
                            parentID);
                        foreach (IOFile file in IOFileList)
                        {
                            uploadFilePath = (compressing == 0) ? file.path : Gtools.compressFile(file.path);
                            filename       = (compressing == 0) ? file.name : file.name.Split('.').First() + ".zip";
                            GoogleDriveAPIV3.uploadToDrive(uploadFilePath, filename, parentID, (onlyNew != 0), new frmMain());
                        }
                    }
                    else
                    {
                        throw new Exception("Connection Error");
                    }
                }
                else
                {
                    throw new Exception("Arguments Error");
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Start with Args Error.\n");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Start with Args Error.\n");
            }
        }
Beispiel #12
0
        private void btnCreateBatch_Click(object sender, EventArgs e)
        {
            string fileListName = Gtools.getTimeStamp() + "_" + UserList[cbUser.SelectedIndex].userName + "_" + txtBackUpName.Text + ".json";
            string fileListPath = Path.Combine(savePath, fileListName);

            saveFileLIst(fileListPath);
            string param1 = fileListPath;                                                       // filelist.json Path parameter
            string param2 = (chbUploadMultiple.Checked)? txtBackUpName.Text : txtFileName.Text; // file Name parameter
            string param3 = (txtParentID.Text != string.Empty) ? txtParentID.Text : "0";        // Parent Id parameter
            int    param4 = cbUser.SelectedIndex;                                               // user index parameter
            int    param5 = (MessageBox.Show("Do you want to Upload only \"new/changed\" files to Google Drive?" +
                                             UserList[cbUser.SelectedIndex].userName, "Uploading Arguments",
                                             MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) ? 1 : 0; // Copy Only new parameter
            int param6 = (chbCompress.Checked) ? 1 : 0;                                                                      // comporess parameter

            string appPath = "\"" + Path.GetFullPath(Application.ExecutablePath) + "\"";


            string contentToWrite = "cls" + Environment.NewLine +
                                    "@ECHO OFF" + Environment.NewLine +
                                    "set param1=\"" + param1 + "\"" + Environment.NewLine +
                                    "set param2=\"" + param2 + "\"" + Environment.NewLine +
                                    "set param3=\"" + param3 + "\"" + Environment.NewLine +
                                    "set param4=\"" + param4 + "\"" + Environment.NewLine +
                                    "set param5=\"" + param5 + "\"" + Environment.NewLine +
                                    "set param6=\"" + param6 + "\"" + Environment.NewLine +
                                    appPath + " %param1% %param2% %param3% %param4% %param5% %param6%";

            FolderBrowserDialog fbd    = new FolderBrowserDialog();
            DialogResult        result = fbd.ShowDialog();

            switch (result)
            {
            case DialogResult.OK:

                Gtools.createFile(Path.Combine(fbd.SelectedPath,
                                               UserList[cbUser.SelectedIndex].userName + "_File_" + txtFileName.Text.Split('.').First() + ".bat")
                                  , contentToWrite);

                break;

            default:
                break;
            }
        }
        public static List <GoogleCaledar> listCalendar()
        {
            List <GoogleCaledar> calList = new List <GoogleCaledar>();

            try
            {
                EventsResource.ListRequest request = calendarService.Events.List("primary");
                request.TimeMin      = DateTime.Now;
                request.ShowDeleted  = false;
                request.SingleEvents = true;
                request.MaxResults   = 10;
                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

                // List events.
                Events events = request.Execute();
                System.Diagnostics.Debug.WriteLine("Upcoming events:");
                if (events.Items != null && events.Items.Count > 0)
                {
                    foreach (var eventItem in events.Items)
                    {
                        string when = eventItem.Start.DateTime.ToString();
                        if (String.IsNullOrEmpty(when))
                        {
                            when = eventItem.Start.Date;
                        }
                        System.Diagnostics.Debug.WriteLine("{0} ({1})", eventItem.Summary, when);
                        calList.Add(new GoogleCaledar(eventItem.Summary, when, eventItem.UpdatedRaw.ToString(), eventItem.Status, eventItem.Id));
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("No upcoming events found.");
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Create Drive Service Error.\n");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Create Drive Service Error.\n");
            }

            return(calList);
        }
 private static bool createDriveService()
 {
     try
     {
         // Create Drive API service.
         driveService = new DriveService(new BaseClientService.Initializer()
         {
             HttpClientInitializer = credential,
             ApplicationName       = applicationName,
         });
         return(true);
     }
     catch (Exception exc)
     {
         System.Diagnostics.Debug.WriteLine(exc.Message + " Create Drive Service Error.\n");
         Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                            Environment.NewLine + exc.Message + " Create Drive Service Error.\n");
         return(false);
     }
 }
 private static bool uploadFileToDrive(string folderId, string fileName, string filePath, string fileType, bool onlyNew, frmMain parentForm)
 {
     if (onlyNew)
     {
         if (!compareHash(Gtools.hashGenerator(filePath)))
         {
             uploadFileToDrive(folderId, fileName, filePath, fileType, parentForm);
             return(true);
         }
         else
         {
             return(false);
         }
     }
     else
     {
         uploadFileToDrive(folderId, fileName, filePath, fileType, parentForm);
         return(true);
     }
 }
        private static void convertMemoryStreamToFileStream(MemoryStream stream, string savePath)
        {
            FileStream fileStream;

            using (fileStream = new System.IO.FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                try
                {
                    // System.IO.File.Create(saveFile)
                    stream.WriteTo(fileStream);
                    fileStream.Close();
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Debug.WriteLine(exc.Message + " Convert Memory stream Error");
                    Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                       Environment.NewLine + exc.Message + " Convert Memory stream Error.\n");
                }
            }
        }
        public static void directoryUpload(string path, string parentId, bool onlyNew, frmMain parentForm)
        {
            try
            {
                // Get the subdirectories for the specified directory.
                string folderId = createFolderToDrive(
                    Path.GetFileName(path),
                    parentId);

                System.Diagnostics.Debug.WriteLine(folderId);

                DirectoryInfo dir = new DirectoryInfo(path);
                if (!dir.Exists)
                {
                    throw new DirectoryNotFoundException(
                              "Source directory does not exist or could not be found: "
                              + path);
                }

                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    uploadFileToDrive(
                        folderId, file.Name,
                        Path.Combine(path, file.Name),
                        getMimeType(file.Name), onlyNew, parentForm);
                }

                DirectoryInfo[] dirs = dir.GetDirectories();
                foreach (DirectoryInfo subdir in dirs)
                {
                    directoryUpload(subdir.FullName, folderId, onlyNew, parentForm);
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Directory upload Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Directory upload Error.\n");
            }
        }
Beispiel #18
0
        private static bool loadFileList(string saveFile)
        {
            try
            {
                if (!System.IO.File.Exists(saveFile))
                {
                    throw new Exception("File not found!");
                }

                IOFileList.Clear();
                IOFileList = Newtonsoft.Json.JsonConvert.DeserializeObject <List <IOFile> >(System.IO.File.ReadAllText(saveFile));
                return(true);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Load User Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Load User Error.\n");
                return(false);
            }
        }
Beispiel #19
0
        private void btnRemUser_Click(object sender, EventArgs e)
        {
            if (cbUser.SelectedIndex != -1)
            {
                DialogResult result = MessageBox.Show("Do you want to delete User: "******"Confirm",
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                switch (result)
                {
                case DialogResult.Yes:
                    Gtools.deleteCredFile(savePath, UserList[cbUser.SelectedIndex].userName);
                    UserList.Remove(UserList[cbUser.SelectedIndex]);
                    saveUsers(saveFile);
                    cbUserInit();
                    break;

                default:
                    break;
                }
            }
        }
Beispiel #20
0
 private void loadUsers(string savePath, string saveFile)
 {
     Directory.CreateDirectory(savePath);
     try
     {
         if (System.IO.File.Exists(saveFile))
         {
             UserList.Clear();
             UserList = JsonConvert.DeserializeObject <List <User> >(System.IO.File.ReadAllText(saveFile));
         }
         else
         {
             Gtools.createFile(saveFile, "[ ]");
             loadUsers(savePath, saveFile);
         }
     }
     catch (Exception exc)
     {
         System.Diagnostics.Debug.WriteLine(exc.Message + " Load User Error.\n");
         Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                            Environment.NewLine + exc.Message + " Load User Error.\n");
     }
 }
Beispiel #21
0
 private void textBox_path_TextChanged(object sender, EventArgs e)
 {
     txtFileName.Text = Path.GetFileName(txtFilePath.Text);
     txtMd5.Text      = Gtools.hashGenerator(txtFilePath.Text);
 }
        public static List <GoogleDriveFile> listDriveFiles(string fileName = null, string fileType = null)
        {
            List <GoogleDriveFile> filesList = new List <GoogleDriveFile>();

            try
            {
                if (fileName == null && fileType == null)
                {
                    FilesResource.ListRequest listRequest = driveService.Files.List();
                    listRequest.PageSize = 1000;
                    listRequest.Fields   = "nextPageToken, files(mimeType, id, name, parents, size, modifiedTime, md5Checksum, webViewLink)";
                    //listRequest.OrderBy = "mimeType";
                    // List files.
                    IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
                    filesList.Clear();
                    if (files != null && files.Count > 0)
                    {
                        foreach (var file in files)
                        {
                            filesList.Add(new GoogleDriveFile(
                                              file.Name,
                                              sizeFix(file.Size.ToString(), file.MimeType),
                                              file.ModifiedTime.ToString(),
                                              file.MimeType,
                                              file.Id, file.Md5Checksum,
                                              file.WebViewLink));
                            System.Diagnostics.Debug.WriteLine("{0} {1} {2} {3}",
                                                               file.Name, file.Id, file.MimeType, file.Size.ToString());
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("No files found.");
                    }
                }
                else
                {
                    string pageToken = null;
                    do
                    {
                        FilesResource.ListRequest request = driveService.Files.List();
                        request.PageSize = 1000;
                        //request.Q = "mimeType='image/jpeg'";
                        request.Q = "name contains '" + fileName + "'";
                        if (fileType != null)
                        {
                            request.Q += "and (mimeType contains '" + fileType + "')";
                        }
                        request.Spaces    = "drive";
                        request.Fields    = "nextPageToken, files(mimeType, id, name, parents, size, modifiedTime, md5Checksum, webViewLink)";
                        request.PageToken = pageToken;
                        var result = request.Execute();
                        foreach (var file in result.Files)
                        {
                            filesList.Add(new GoogleDriveFile(
                                              file.Name,
                                              sizeFix(file.Size.ToString(), file.MimeType),
                                              file.ModifiedTime.ToString(),
                                              file.MimeType,
                                              file.Id, file.Md5Checksum,
                                              file.WebViewLink));
                        }
                        pageToken = result.NextPageToken;
                    } while (pageToken != null);
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Drivefile list Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Drivefile list Error.\n");
            }
            return(filesList);
        }
        public static void downloadFromDrive(string filename, string fileId, string savePath, string mimeType, frmMain parentForm)
        {
            frmMain parent    = parentForm;
            long    totalSize = 100000;

            parent.updateStatusBar(0, "Downloading...");
            try
            {
                if (Path.HasExtension(filename))
                {
                    var request = driveService.Files.Get(fileId);

                    var stream = new System.IO.MemoryStream();
                    System.Diagnostics.Debug.WriteLine(fileId);
                    // 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 +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            System.Diagnostics.Debug.WriteLine(progress.BytesDownloaded);

                            parent.updateStatusBar((progress.BytesDownloaded * 100) / totalSize, "Downloading...");
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Download complete.");
                            System.Diagnostics.Debug.WriteLine("Download complete.");
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Download failed.");
                            System.Diagnostics.Debug.WriteLine("Download failed.");
                            MessageBox.Show("File failed to download!!!", "Download Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        }
                    };
                    request.Download(stream);
                    convertMemoryStreamToFileStream(stream, savePath + @"\" + @filename);
                    stream.Dispose();
                }
                else
                {
                    string extension = "", converter = "";
                    foreach (MimeTypeConvert obj in MimeConverter.mimeList())
                    {
                        if (mimeType == obj.mimeType)
                        {
                            extension = obj.extension;
                            converter = obj.converterType;
                        }
                    }
                    System.Diagnostics.Debug.WriteLine("{0} {1} {2}", fileId, extension, mimeType);
                    var request = driveService.Files.Export(fileId, converter);
                    var stream  = new System.IO.MemoryStream();
                    // 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 +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            Console.WriteLine(progress.BytesDownloaded);
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Download Complete!");
                            Console.WriteLine("Download complete.");
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Download failed.");
                            Console.WriteLine("Download failed.");
                            MessageBox.Show("File failed to download!!!", "Download Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        }
                    };
                    request.Download(stream);
                    convertMemoryStreamToFileStream(stream, savePath + @"\" + @filename + extension);
                    stream.Dispose();
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Download From Drive Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Download From Drive.\n");
            }
        }
        private static bool uploadFileToDrive(string folderId, string fileName, string filePath, string fileType, frmMain parentForm)
        {
            frmMain parent = parentForm;

            parent.updateStatusBar(0, "Uploading...");
            long totalSize = 100000;

            try
            {
                FileInfo fi = new FileInfo(filePath);
                totalSize = fi.Length;

                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = fileName
                };
                if (folderId != null)
                {
                    fileMetadata.Parents = new List <string>
                    {
                        folderId
                    };
                }
                FilesResource.CreateMediaUpload request;
                using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
                {
                    request = driveService.Files.Create(
                        fileMetadata, stream, fileType);
                    request.ChunkSize        = FilesResource.CreateMediaUpload.MinimumChunkSize;
                    request.ProgressChanged += (IUploadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case UploadStatus.Uploading:
                        {
                            parent.updateStatusBar((progress.BytesSent * 100) / totalSize, "Uploading...");
                            System.Diagnostics.Debug.WriteLine(progress.BytesSent);
                            break;
                        }

                        case UploadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Upload complete.");
                            System.Diagnostics.Debug.WriteLine("Upload complete.");
                            break;
                        }

                        case UploadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Upload failed.");
                            System.Diagnostics.Debug.WriteLine("Upload failed.");
                            //MessageBox.Show("File failed to upload!!!", "Upload Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                               Environment.NewLine + "Upload failed.\n");
                            break;
                        }
                        }
                    };
                    request.Fields = "id";
                    request.Upload();
                }
                var file = request.ResponseBody;
                System.Diagnostics.Debug.WriteLine("File ID:{0} \n FileName {1} ", file.Id, file.Name);
                return(true);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Upload file to Drive Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Upload file to Drive Error.\n");
                return(false);
            }
        }