/// <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); } }
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; })); }
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"); } }
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 async Task <ActionResult> UpdateGoogleFileAsync(string id, CancellationToken cancellationToken) { var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(cancellationToken); if (result.Credential != null) { var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "WorkCard.vn" }); var list = await service.Files.List().ExecuteAsync(); var _item = list.Items.Where(t => t.Id == id).FirstOrDefault(); try { if (!_item.Description.Contains("WorkCard.vn")) { _item.Description += "WorkCard.vn"; } _item.Shared = true; _item.CanComment = true; _item.Capabilities.CanDownload = true; _item.Capabilities.CanShare = true; FilesResource.UpdateRequest request = service.Files.Update(_item, _item.Id); request.NewRevision = true; await request.ExecuteAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } if (!_item.DownloadUrl.IsNullOrEmptyOrWhiteSpace()) { using (ApplicationDbContext context = new ApplicationDbContext()) { var file = context.Documents.Where(t => t.GDriveId == id).FirstOrDefault(); file.DownloadUrl = _item.DownloadUrl; context.Entry(file).State = EntityState.Modified; await context.SaveChangesAsync(); } } if (Request.IsAjaxRequest()) { return(PartialView("_NotifyMessage", "Downloaded")); } return(View("_NotifyMessage", "Downloaded")); } else { return(new RedirectResult(result.RedirectUri)); } }
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(); }
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); }
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 void AppendOneFile(DriveService ds, RoutedPodioEvent e, File addMe, File book) { //var reader = PdfSharp.Pdf.IO.PdfReader.Open() try { var export = new FilesResource.ExportRequest(ds, addMe.Id, "application/pdf").Execute(); //var merged = new File(); //var pdf = new PdfSharp.Pdf.PdfDocument(); var result = new FilesResource.UpdateRequest(ds, addMe, book.Id).Execute(); } catch (Exception ex) { Console.WriteLine($"{e.podioEvent.item_id} - {ex.Message} - {ex.StackTrace} - {ex.InnerException}"); } }
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); }
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); }
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); }
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(); }
/// <summary> /// This is the method that can be used to copy a file from one folder into another in folder /// in Google Drive. /// </summary> /// <param name="fromFolder">The folder to copy from</param> /// <param name="toFolder">The folder to copy into</param> /// <param name="fileName">The name of the file to be copied</param> /// <returns>The copied file</returns> public static async Task <Google.Apis.Drive.v3.Data.File> CopyFileToNewLocation(string fromFolder, string toFolder, string fileName) { DriveService service = CreateService(); string fileId = null, fromFolderId = null, toFolderId = null; Google.Apis.Drive.v3.Data.File filedata; // Get all the files in the Google Drive FilesResource.ListRequest fileListRequest = service.Files.List(); fileListRequest.Fields = "nextPageToken, files(*)"; //get file in the root folder. IList <Google.Apis.Drive.v3.Data.File> rootFolderFiles = fileListRequest.Execute().Files; //Get the Id of the fromfolder if (rootFolderFiles != null && rootFolderFiles.Count > 0) { foreach (var file in rootFolderFiles) { if (file.Name.ToLower() == fromFolder.ToLower()) { fromFolderId = file.Id; break; } } } //Throw an exception if the fromFolderId is still null indicating that the from folder doesn't exist if (fromFolderId == null) { throw new GoogleApiException("Source folder doesn't exist"); } //Get te Id of the toFolder if (rootFolderFiles != null && rootFolderFiles.Count > 0) { foreach (var file in rootFolderFiles) { if (file.Name.ToLower() == toFolder.ToLower()) { toFolderId = file.Id; break; } } } //Throw an exception if the toFolderId is still null indicating that the to folder doesn't exist if (toFolderId == null) { throw new GoogleApiException("Destination folder doesn't exist"); } //Get the Id and meatadata of the file in the fromFolder if (rootFolderFiles != null && rootFolderFiles.Count > 0) { foreach (var file in rootFolderFiles) { foreach (var parent in file.Parents) { if (parent == fromFolderId && file.Name == fileName) { fileId = file.Id; filedata = file; break; } } } } //Throw an exception to indicate that the file doesn't exist in the from folder if (fileId == null) { throw new GoogleApiException("File does not exist in the folder"); } //copy the file to a new location FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId); updateRequest.Fields = "*"; updateRequest.AddParents = toFolderId; //Execute the request filedata = await updateRequest.ExecuteAsync(); return(filedata); }
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); } }
public static FilesResource.UpdateRequest AsFileSystem(this FilesResource.UpdateRequest request, DirectoryId parent, DirectoryId destination) { request.RemoveParents = parent.Value; request.AddParents = destination.Value; return(request.AsFileSystem()); }
public static FilesResource.UpdateRequest AsFileSystem(this FilesResource.UpdateRequest request) { request.Fields = "id,name,createdTime,modifiedTime,size,md5Checksum"; return(request); }