public static Task <bool> MoveToTrash(string id)
        {
            return(Task.Run(() =>
            {
                bool success = false;

                try
                {
                    File file = new File()
                    {
                        Trashed = true
                    };

                    FilesResource.UpdateRequest deleteRequest = Service.Files.Update(file, id);
                    deleteRequest.Fields = "id, name, trashed";

                    File r = deleteRequest.Execute();

                    success = r.Trashed.GetValueOrDefault();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                return success;
            }));
        }
Example #2
0
        public static string MoveFiles(String fileId, String folderId)
        {
            DriveService service = GetService();

            // Retrieve the existing parents to remove
            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);

            // Move the file to the new folder
            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");
            }
        }
 /// <summary>
 /// Untrash a file on Google Drive: GooglDriveService.Files.Updaate
 /// Instead of permanently deleting a file you can simply trash it.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="fileId"></param>
 /// <returns></returns>
 public GoogleDriveManagerResult UnTrashFile(DriveService service, string fileId)
 {
     result = new GoogleDriveManagerResult();
     try
     {
         Google.Apis.Drive.v3.Data.File response = null;
         Google.Apis.Drive.v3.Data.File file     = new Google.Apis.Drive.v3.Data.File();
         if ((bool)file.OwnedByMe)
         {
             file.Trashed = false;
             FilesResource.UpdateRequest request = service.Files.Update(file, fileId);
             response = request.Execute();
             if (response != null)
             {
                 result.GoogleDriveFileId = response.Id;
             }
             else
             {
                 result.Errors.Add(GoogleDriveManagementConstants.UnTrashingFileError);
             }
         }
         else
         {
             result.Errors.Add(GoogleDriveManagementConstants.FileNotOwnedByUserError);
         }
         return(result);
     }
     catch (Exception e)
     {
         WriteToConsole(GoogleDriveManagementConstants.UnTrashingFileException + e.Message);
         result.Exceptions.Add(e);
         return(result);
     }
 }
Example #4
0
            protected override void Start()
            {
                try
                {
                    if (Status != StatusType.Queued)
                    {
                        throw new Exception("Stream has not been queued.");
                    }

                    base.Start();

                    _FileInfo = _DriveService.GetFile(FileId);

                    if (_FileInfo == null)
                    {
                        throw new Exception("File '" + FileId + "' no longer exists.");
                    }

                    Lock();

                    using (API.DriveService.Connection connection = API.DriveService.Connection.Create())
                    {
                        Google.Apis.Drive.v2.Data.File file = _FileInfo._file;

                        file = connection.Service.Files.Get(file.Id).Execute();

                        file.Title = Title;

                        if (!String.IsNullOrEmpty(MimeType))
                        {
                            file.MimeType = MimeType;
                        }

                        FilesResource.UpdateRequest request = connection.Service.Files.Update(file, FileId);

                        file = request.Execute();

                        _FileInfo = GetFileInfo(file);

                        DriveService_ProgressChanged(StatusType.Completed, null);
                    }
                }
                catch (Exception exception)
                {
                    try
                    {
                        _Status           = StatusType.Failed;
                        _ExceptionMessage = exception.Message;

                        DriveService_ProgressChanged(StatusType.Failed, exception);
                    }
                    catch
                    {
                        Debugger.Break();
                    }

                    Log.Error(exception);
                }
            }
        public void MoveOrphanFilesToParent(string globalRestoredFolderId, List <DriveItem> orphansToMove)
        {
            for (int i = 0; i < orphansToMove.Count; i++)
            {
                Console.Write("\rMoving orphan back into parent folder... {0}/{1}", i + 1, orphansToMove.Count);
                FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), orphansToMove[i].id.Replace("items/", ""));
                updateRequest.AddParents    = orphansToMove[i].parent_id.Replace("items/", "");
                updateRequest.RemoveParents = globalRestoredFolderId;

                var response = updateRequest.Execute();
            }
            Console.WriteLine();
        }
Example #6
0
        void CopyFiles()
        {
            Google.Apis.Drive.v3.Data.File file1 = new Google.Apis.Drive.v3.Data.File();
            file1.Name = $"{DateTime.Now.ToString("yyyy-MM-dd HH-mm")} - Sao Lưu";
            FilesResource.CopyRequest updateRequest1 = DService.Files.Copy(file1, SpreadsheetId);
            updateRequest1.Fields = "id, parents, name";
            file1 = updateRequest1.Execute();

            FilesResource.UpdateRequest updateRequest = DService.Files.Update(new Google.Apis.Drive.v3.Data.File(), file1.Id);
            updateRequest.Fields     = "id, parents";
            updateRequest.AddParents = "1i05huRMast4E7XPi3twLeAcWvTkdakJO";

            file1 = updateRequest.Execute();
        }
        public static Google.Apis.Drive.v2.Data.File createDirectory(DriveService _service, string _title, string _description, string _id)
        {
            if (!CheckInternetConnection())
            {
                return(null);
            }
            Google.Apis.Drive.v2.Data.File NewDirectory = null;

            // Create metaData for a new Directory
            var body = new Google.Apis.Drive.v2.Data.File();

            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = "application/vnd.google-apps.folder";

            // TODO: Remove this

            /*
             * body.UserPermission = new Permission
             * {
             *  Type = "anyone",
             *  Role = "reader",
             *  WithLink = true
             * };
             */

            try
            {
                if (_id != null)
                {
                    FilesResource.UpdateRequest request = _service.Files.Update(body, _id);
                    NewDirectory = request.Execute();
                }
                else
                {
                    FilesResource.InsertRequest request = _service.Files.Insert(body);
                    NewDirectory = request.Execute();
                }
            }
            catch (Exception e)
            {
                new MaterialDialog("An unexpected error occured", "It looks like something went wrong. If you have an idea, email me at [email protected] or open an issue over at Github!\n\n\n" + e.Message, 500).ShowDialog();
                return(null);
            }

            insertPermission(_service, NewDirectory.Id);
            return(NewDirectory);
        }
Example #8
0
        public void Rename(string fileID, string fileName, string extensionOfLocal, string newName)
        {
            string uploadType = SelectContentType(extensionOfLocal);

            try
            {
                Google.Apis.Drive.v3.Data.File SelectedFile = service.Files.Get(fileID).Execute();
                SelectedFile.Name = newName + "." + extensionOfLocal;
                FilesResource.UpdateRequest request = service.Files.Update(SelectedFile, fileID);
                request.Execute();
            }
            catch (Exception e)
            {
                MessageBox.Show("Rename of the file is failed: " + fileName);
            }
        }
        public FileManagerResponse Move(string path, string targetPath, string[] names, string[] replacedItemNames, FileManagerDirectoryContent TargetData, params FileManagerDirectoryContent[] data)
        {
            FileManagerResponse moveResponse             = new FileManagerResponse();
            DriveService        service                  = GetService();
            List <FileManagerDirectoryContent> moveFiles = new List <FileManagerDirectoryContent>();

            ChildrenResource.ListRequest request = service.Children.List(data[0].Id);
            ChildList     children      = request.Execute();
            List <string> childFileList = children.Items.Select(x => x.Id).ToList();

            if (childFileList.IndexOf(TargetData.Id) != -1)
            {
                ErrorDetails er = new ErrorDetails();
                er.Code            = "400";
                er.Message         = "The destination folder is the subfolder of the source folder.";
                moveResponse.Error = er;
                return(moveResponse);
            }
            foreach (FileManagerDirectoryContent item in data)
            {
                FilesResource.GetRequest fileRequest = service.Files.Get(item.Id);
                fileRequest.Fields = "parents";
                var    file            = fileRequest.Execute();
                string previousParents = String.Join(",", file.Parents.Select(t => t.Id));
                FilesResource.UpdateRequest moveRequest = service.Files.Update(new File(), item.Id);
                moveRequest.Fields        = "id, parents";
                moveRequest.AddParents    = TargetData.Id;
                moveRequest.RemoveParents = previousParents;
                file = moveRequest.Execute();
                File filedetails = service.Files.Get(file.Id).Execute();
                FileManagerDirectoryContent FileDetail = new FileManagerDirectoryContent();
                FileDetail.Name         = filedetails.Title;
                FileDetail.Id           = filedetails.Id;
                FileDetail.IsFile       = filedetails.MimeType == "application/vnd.google-apps.folder" ? false : true;
                FileDetail.Type         = filedetails.FileExtension == null ? "folder" : filedetails.FileExtension;
                FileDetail.HasChild     = getChildrenById(filedetails.Id);
                FileDetail.Size         = item.Size;
                FileDetail.FilterPath   = targetPath.Replace("/", @"\");
                FileDetail.FilterId     = obtainFilterId(filedetails);
                FileDetail.DateCreated  = Convert.ToDateTime(filedetails.ModifiedDate);
                FileDetail.DateModified = Convert.ToDateTime(filedetails.ModifiedDate);
                moveFiles.Add(FileDetail);
            }
            moveResponse.Files = moveFiles;
            return(moveResponse);
        }
Example #10
0
            public AttemptResult RenameFile(string id, string new_filename)
            {
                FilesResource.UpdateRequest request = drive_service.Files.Update(
                    new Google.Apis.Drive.v3.Data.File()
                {
                    Name = new_filename
                },
                    id
                    );

                try
                {
                    request.Execute();
                }
                catch (Google.GoogleApiException exception)
                {
                    return(exception.Error.GetAttemptResult());
                }

                return(AttemptResult.Succeeded);
            }
Example #11
0
        public async Task <File> UpdateAsync(File file)
        {
            string result = string.Empty;

            await AuthenticationAsync();

            string Description = "This is automatic update description for file";

            file.Description = Description;

            File body = new File();

            body.Name        = file.Name;
            body.Description = "File updated by Diamto Drive Sample";
            body.MimeType    = GetMimeType(file.MimeType);
            body.Parents     = file.Parents;

            FilesResource.UpdateRequest request = Service.Files.Update(body, file.Id);
            var model = request.Execute();

            return(model);
        }
Example #12
0
            protected override void Start()
            {
                try
                {
                    if (Status != StatusType.Queued)
                    {
                        throw new Exception("Stream has not been queued.");
                    }

                    base.Start();

                    _FileInfo = _DriveService.GetFile(FileId);

                    if (_FileInfo == null)
                    {
                        throw new Exception("File '" + FileId + "' no longer exists.");
                    }

                    Lock();

                    if (_FileInfo.ParentId == ParentId)
                    {
                        DriveService_ProgressChanged(StatusType.Completed, null);
                    }
                    else
                    {
                        FileInfoStatus currentStatus = API.DriveService.GetFileInfoStatus(_FileInfo);

                        Google.Apis.Drive.v2.Data.File file = _FileInfo._file;

                        using (API.DriveService.Connection connection = API.DriveService.Connection.Create())
                        {
                            file = connection.Service.Files.Get(file.Id).Execute();

                            if (file.Parents.Count > 0)
                            {
                                file.Parents.RemoveAt(0);
                            }

                            var parentReference = new ParentReference {
                                Id = _ParentId
                            };

                            file.Parents.Insert(0, parentReference);

                            FilesResource.UpdateRequest request = connection.Service.Files.Update(file, FileId);

                            file = request.Execute();

                            _FileInfo = GetFileInfo(file);

                            FileInfoStatus newStatus = API.DriveService.GetFileInfoStatus(_FileInfo);

                            if (currentStatus == FileInfoStatus.OnDisk)
                            {
                                DateTime modifiedDate = API.DriveService.GetDateTime(file.ModifiedDate);

                                try
                                {
                                    API.DriveService.SetFileLastWriteTime(_FileInfo.FilePath, modifiedDate);
                                }
                                catch
                                {
                                }

                                _FileInfo = GetFileInfo(file);

                                newStatus = API.DriveService.GetFileInfoStatus(_FileInfo);
                            }

                            DriveService_ProgressChanged(StatusType.Completed, null);
                        }
                    }
                }
                catch (Exception exception)
                {
                    try
                    {
                        _Status           = StatusType.Failed;
                        _ExceptionMessage = exception.Message;

                        DriveService_ProgressChanged(StatusType.Failed, exception);
                    }
                    catch
                    {
                        Debugger.Break();
                    }

                    Log.Error(exception);
                }
            }
Example #13
0
        private void PutDriveFilesInGSheet()
        {
            // Get the sheets currently in the GSheet.

            // Define request parameters.
            SpreadsheetsResource.ValuesResource.GetRequest request = SheetsService.Spreadsheets.Values.Get(SpreadsheetId, _sheetRange);

            // Temp list of each row in the spreadsheet
            IList <IList <Object> > gSheetRowsExisting = request.Execute().Values;

            // Temp list of each new row to add to the spreadsheet.
            IList <IList <Object> > gSheetRowsNew = new List <IList <object> >();

            // If the existing response returns with values.
            if (gSheetRowsExisting != null && gSheetRowsExisting.Count > 0)
            {
                foreach (DriveFileVM file in DriveFiles)
                {
                    // If no row exists with the specified Id, add a new row to the spreadsheet.
                    if (gSheetRowsExisting.Where(row => row[0].ToString() == file.FileId).Count() == 0)
                    {
                        gSheetRowsNew.Add(new List <object>()
                        {
                            file.FileId, file.FileName, file.DriveFileType, file.DriveLink
                        });
                    }
                    else if (gSheetRowsExisting.Where(row => row[0].ToString() == file.FileId).Count() == 1) // If a sheet already exists
                    {
                        // Get the spreadsheet version of the file to be renamed.
                        var gSheetDriveFile = gSheetRowsExisting.Where(row => row[0].ToString() == file.FileId).First();

                        // Get the google drive file corresponding to the file in the sheet.
                        Google.Apis.Drive.v2.Data.File driveFileToBeRenamed = DriveService.Files.Get(gSheetDriveFile[0].ToString()).Execute();

                        // Set this to null as it can't be overwritten.
                        driveFileToBeRenamed.Id = null;

                        string newName = gSheetDriveFile[1].ToString();

                        // Only rename the file if it has a new name.
                        if (driveFileToBeRenamed.Title != newName)
                        {
                            driveFileToBeRenamed.Title = newName;
                            FilesResource.UpdateRequest updateRequest = DriveService.Files.Update(driveFileToBeRenamed, gSheetDriveFile[0].ToString());
                            updateRequest.Execute();
                        }
                    }
                }
            }
            else // Sheet is empty
            {
                foreach (DriveFileVM file in DriveFiles)
                {
                    gSheetRowsNew.Add(new List <object>()
                    {
                        file.FileId, file.FileName, file.DriveFileType, file.DriveLink, file.OriginalFileName
                    });
                }
            }

            // The values to append into the range.
            var valueRange = new ValueRange
            {
                Values = gSheetRowsNew
            };

            // Create a request to append the values in the spreadsheet, adds new values as new lines.
            var appendRequest = SheetsService.Spreadsheets.Values.Append(valueRange, SpreadsheetId, _sheetRange);

            // The data should be interpreted as user entered.
            appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;

            // Execute the request
            var appendResponse = appendRequest.Execute();
        }