/// <summary> /// Used to download the first Google Drive file that matches the given query. /// </summary> /// <param name="query">The query to apply to the ListRequest. See the Drive API docs for supported syntax</param> /// <returns>A stream for the first found file, or null if no file was found</returns> public MemoryStream GetFirstFileStream(string query) { // Get the first file that matches the given query GoogleDriveData.FileList listFilesResult = ListFiles(query, 1); if (listFilesResult.Files == null || listFilesResult.Files.Count < 1) { return(null); } // Return the stream for the first file return(GetGoogleDriveFileStream(listFilesResult.Files[0])); }
/// <summary> /// Used to get the Google Drive file at the specified path. /// </summary> /// <param name="filePath">The path of a file on Google Drive</param> /// <returns>The requested file or null if it couldn't be found</returns> public GoogleDriveData.File GetGoogleDriveFile(string filePath) { // Get the Drive service DriveService service = GetDriveService(); // Escape any apostrophes in the file path filePath = filePath.Replace("'", "\\'"); // Split the file path at forward slashes string[] fileSections = filePath.Split('/'); // Go through each file section, working our way down the file path string parentID = null; GoogleDriveData.File file = null; for (int sectionIndex = 0; sectionIndex < fileSections.Length; sectionIndex++) { string section = fileSections[sectionIndex]; // If this is the last file section then that means it's the file name bool sectionIsFile = (sectionIndex == fileSections.Length - 1); // Create the request to find the folder/file FilesResource.ListRequest listRequest = service.Files.List(); // Set the query for the list request if (sectionIsFile) { listRequest.Q = "name = '" + section + "'"; } else { listRequest.Q = "mimeType = 'application/vnd.google-apps.folder' and name = '" + section + "'"; } // If the parent ID isn't null, then add it to the list request query if (parentID != null) { listRequest.Q += " and '" + parentID + "' in parents"; } // Do the request GoogleDriveData.FileList fileList = listRequest.Execute(); // If no files/folders were found then that means the file must not exist if (fileList.Files == null || fileList.Files.Count == 0) { break; } // If the file returned is a file then we have found what we are looking for GoogleDriveData.File currentFileOrFolder = fileList.Files.First(); if (sectionIsFile) { file = currentFileOrFolder; break; } else { // Get the ID of the current folder parentID = currentFileOrFolder.Id; } } return(file); }