private static DriveFileInfo GetDriveFolder(DriveClient client, string rootFolderId, IEnumerable <string> pathItems, bool createIfNotExists = false) { DriveFileInfo currentFolder = null; string currentId = rootFolderId; foreach (var pathItem in pathItems) { var getRequest = new DriveFileListRequest { MaxResults = 4, Query = string.Format("trashed = false and title = '{0}' and mimeType = 'application/vnd.google-apps.folder'", pathItem) }; var getResponse = client.Execute(getRequest); currentFolder = getResponse.Data.Items.FirstOrDefault(); if (currentFolder == null) { if (!createIfNotExists) { break; } var createRequest = new DriveFolderCreateRequest(new DriveFolderShortInfo { Title = pathItem, Parents = new List <DriveParentReferenceInfo> { new DriveParentReferenceInfo { Id = currentId } } }); var createResponse = client.Execute(createRequest); currentFolder = createResponse.Data; } currentId = currentFolder.Id; } return(currentFolder); }
public void DownloadFile() { Task.Factory.StartNew(() => { try { IsDownloadingEnabled = false; IsDownloadingInProgress = true; if (AccessToken == null) { throw new InvalidOperationException("The client is not authorized."); } var fileInfo = new FileInfo(PathToLocalDownloadedFile); if (fileInfo.Exists) { throw new InvalidOperationException(string.Format("File \"{0}\" already exists.", fileInfo.FullName)); } string[] pathItems = PathToRemoteDownloadedFile.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); if (pathItems.Length == 0) { throw new InvalidOperationException("Path to remote file is empty"); } string fileTitle = pathItems.Last(); string[] folderItems = pathItems.Length > 1 ? pathItems.Take(pathItems.Length - 1).ToArray() : null; var folderInfo = GetDriveFolder(Client, DriveAbout.RootFolderId, folderItems); if (folderItems != null && folderInfo == null) { throw new InvalidOperationException(string.Format("Folder \"{0}\" on Google Drive not found", string.Join("/", folderItems))); } var fileListRequest = new DriveFileListRequest { MaxResults = 4, Query = string.Format("mimeType != 'application/vnd.google-apps.folder' and trashed = false and title = '{0}' and '{1}' in parents", fileTitle, folderInfo != null ? folderInfo.Id : DriveAbout.RootFolderId) }; var fileListResponse = Client.Execute(fileListRequest); var remoteFileInfo = fileListResponse.Data.Items.FirstOrDefault(); if (remoteFileInfo == null) { throw new InvalidOperationException("Remote file not found"); } using (var fileStream = fileInfo.OpenWrite()) { var downloadRequest = new DriveFileDownloadRequest(remoteFileInfo, fileStream); downloadRequest.DownloadProgress += (sender, args) => { var progress = (args.Position / (double)args.Length) * 100; DownloadingProgress = progress; }; Client.Execute(downloadRequest); } } catch (Exception exception) { RaiseErrorEvent(exception); } finally { IsDownloadingEnabled = true; IsDownloadingInProgress = false; DownloadingProgress = 0; } }); }