public void Download(string fileId, string dst) { FilesResource.GetRequest request = this.Service.Files.Get(fileId); request.MediaDownloader.ProgressChanged += this.GoogleDriveDownloadProgress; using var stream = new FileStream(dst, FileMode.Create); request.Download(stream); }
/// <summary> /// Download file from google drive /// </summary> /// <param name="fileId">Downloaded file ID</param> /// <returns>Server file path in server</returns> public static async Task <string> DownloadFileAsync(string fileId) { FilesResource.GetRequest request = GetGoogleDriveService().Files.Get(fileId); string fileName = request.Execute().Name; string filePath = Path.Combine(Path.GetTempPath(), fileName); MemoryStream stream = new MemoryStream(); request.MediaDownloader.ProgressChanged += progress => { switch (progress.Status) { case DownloadStatus.Completed: SaveFile(stream, filePath); break; case DownloadStatus.Downloading: case DownloadStatus.Failed: break; } }; await request.DownloadAsync(stream); return(filePath); }
private static string DownloadFile(DriveService service, string fileid) { string Folderpath = "DriveFiles"; FilesResource.GetRequest request = service.Files.Get(fileid); string filename = request.Execute().Name; string filepath = System.IO.Path.Combine(Folderpath, filename); MemoryStream memorystream = new MemoryStream(); request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { break; } case DownloadStatus.Completed: { SaveStream(memorystream, filepath); break; } case DownloadStatus.Failed: { break; } } }; request.Download(memorystream); return(filepath); }
public static void DownloadFile(FilesResource.GetRequest getRequest, string saveTo) { 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. getRequest.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case Google.Apis.Download.DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case Google.Apis.Download.DownloadStatus.Completed: { Console.WriteLine("Download complete."); SaveStream(stream, saveTo); break; } case Google.Apis.Download.DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; getRequest.Download(stream); }
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"); } }
public bool ReadFile(String fileName) { try { if (SearchFile(fileName)) { MemoryStream stream = new MemoryStream(); FilesResource.GetRequest getRequest = driveService.Files.Get(driveFile.Id); getRequest.Download(stream); stream.Position = 0; StreamReader reader = new StreamReader(stream); fileData = reader.ReadToEnd(); fileData = removeNewLineCharacters(fileData); } else { Debug.WriteLine("Error searching for file"); return false; } return true; }catch (Exception e) { Debug.WriteLine("Error ... " + e.Message); return false; } }
// recurse up the "folder hierarchy" // as is known Google Drive folders structure is pretty loose about hierarchy, everything is done // with pointers and labels, for example: a file may have more than one parent // anyway, for simplicity I'll treat it like an ordinary file system structure, picking the // first parent of a file/folder private string GetFullPath(string id) { CacheEntry folder; if (id == "") { return(""); } if (folderscache.ContainsKey(id)) { folder = folderscache[id]; } else { // get metadata of the folder FilesResource.GetRequest request = service.Files.Get(id); request.Fields = "title,parents/id"; File file = request.Execute(); if (file.Parents.Count > 0) { folder = new CacheEntry(file.Title, file.Parents[0].Id); } else { // no parents folder = new CacheEntry(file.Title, ""); } folderscache.Add(id, folder); } return(GetFullPath(folder.parentid) + "/" + folder.title); }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <returns></returns> private void DownloadFile(FilesResource.GetRequest request, string path) { MemoryStream downloadStream = new MemoryStream(); request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { this.logger.Debug($"Downloading games data archive (Downloaded {progress.BytesDownloaded} bytes."); break; } case DownloadStatus.Completed: { this.logger.Debug($"Finished downloading games data archive."); System.IO.File.WriteAllBytes(path, downloadStream.ToArray()); // TODO: Add notification. break; } case DownloadStatus.Failed: { this.logger.Error($"Could not download games data archive from Google Drive. Exception: {progress.Exception}"); // TODO: Add error notification. break; } } }; request.Download(downloadStream); }
public static string GetLink(string id) { FilesResource.GetRequest getRequest = Instance._service.Files.Get(id); getRequest.Fields = "webViewLink"; Google.Apis.Drive.v3.Data.File f = getRequest.Execute(); return(f.WebViewLink); }
private static void DownloadFolder(string folderId, string parentFolderPath) { FilesResource.GetRequest request = driveService.Files.Get(folderId); request.Fields = "name,mimeType"; GoogleFile fileInfo = request.Execute(); //Makesure metadata gives a folder type if (fileInfo.MimeType != folderMimeType) { Debug.LogWarning($"{folderId} is not a folder"); return; } IList <GoogleFile> subFolders = ListFolders(folderId); IList <GoogleFile> subFiles = ListFiles(folderId); string pathToNewFolder = parentFolderPath.Replace("/", "\\") + $"\\{fileInfo.Name}"; Directory.CreateDirectory(pathToNewFolder); //Download files in current folder foreach (GoogleFile subFile in subFiles) { DownloadFile(subFile.Id, pathToNewFolder); } //Recursively download subfolder stuff foreach (GoogleFile subFolder in subFolders) { DownloadFolder(subFolder.Id, pathToNewFolder); } }
public GoogleDriveManagerResult GetFile(DriveService service, string fileId) { result = new GoogleDriveManagerResult(); try { FilesResource.GetRequest request = service.Files.Get(fileId); Google.Apis.Drive.v3.Data.File file = request.Execute(); if (file != null) { GoogleDriveFile gdf = new GoogleDriveFile() { Id = file.Id, Name = file.Name, Size = file.Size, Version = file.Version, CreatedTime = file.CreatedTime }; result.GoogleDriveFile = gdf; } else { WriteToConsole(GoogleDriveManagementConstants.FileNotFound + fileId); result.Errors.Add(GoogleDriveManagementConstants.FileNotFound); } return(result); } catch (Exception e) { result.Exceptions.Add(e); WriteToConsole(GoogleDriveManagementConstants.GettingFileException + fileId); return(result); } }
private FilesResource.GetRequest formGetRequest(string fileID) { var driveService = InitializeAPI.googleDriveService; FilesResource.GetRequest getRequest = driveService.Files.Get(fileID); return(getRequest); }
public static MemoryStream GetAudioFile(string id) { FilesResource.GetRequest getRequest = Instance._service.Files.Get(id); var stream = new MemoryStream(); getRequest.Download(stream); return(stream); }
public async Task <FileInfo> GetFileInfoAsync(string id) { FilesResource.GetRequest request = _driveService.Files.Get(id); request.Fields = GetFields; File file = await request.ExecuteAsync(); return(GetInfo(file)); }
public void DownloadDatabase() { // Define parameters of request. FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = (IList <Google.Apis.Drive.v3.Data.File>)GetDriveFiles(); if (files != null && files.Count > 0) { foreach (var file in files) { if (file.Name.IndexOf(".db") != -1) { DirectoryInfo directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); FileInfo[] fileInfo = directory.GetFiles(file.Name); if (fileInfo.Length != 0) { foreach (var delete in fileInfo) { delete.Delete(); } } FilesResource.GetRequest request = service.Files.Get(file.Id); MemoryStream stream = new System.IO.MemoryStream(); request.Download(stream); request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { if (progress.Status == DownloadStatus.Completed) { new MessageForm("successful").Show(); } else if (progress.Status == DownloadStatus.Failed) { MessageForm errorForm = new MessageForm("Failed to download database"); errorForm.Show(); } }; using (System.IO.FileStream download = new FileStream(AppDomain.CurrentDomain.BaseDirectory + @"\database.db", FileMode.Create, FileAccess.Write)) { download.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length); } stream.Flush(); stream.Close(); } } } }
public async Task <MemoryStream> DownloadFile(string Id) { MemoryStream downloadedFile = new MemoryStream(); FilesResource.GetRequest getRequest = service.Files.Get(Id); await getRequest.DownloadAsync(downloadedFile); return(downloadedFile); }
private async Task <DriveFile> GetParentFolderDo(string folderId) { FilesResource.GetRequest request = _service.Files.Get(folderId); request.Fields = "id, name, parents"; DriveFile folder = await request.ExecuteAsync(); request = _service.Files.Get(folder.Parents[0]); return(await request.ExecuteAsync()); }
public IList <Google.Apis.Drive.v3.Data.Permission> GetPremissionDetails(string fileId) { FilesResource.GetRequest getReq = service.Files.Get(fileId); getReq.Fields = "permissions"; Google.Apis.Drive.v3.Data.File file = getReq.Execute(); return(file.Permissions); }
public static FilesResource.GetRequest StartDownload(string id, System.IO.FileStream fileStream, CancellationToken cancellationToken) { FilesResource.GetRequest downlodRequest = new FilesResource.GetRequest(Service, id); downlodRequest.MediaDownloader.ChunkSize = ResumableUpload.MinimumChunkSize; downlodRequest.DownloadAsync(fileStream, cancellationToken); return(downlodRequest); }
/// <summary> /// Downloads a remote file from Google Drive, as a readable stream. /// </summary> /// <param name="fullFilename">The Id of the remote file to download from Google Drive.</param> /// <returns>Returns a readable stream representing the remote file to download.</returns> public async Task <Stream> Download(string fullFilename) { var stream = new MemoryStream(); FilesResource.GetRequest request = driveService.Files.Get(fullFilename); await request.DownloadAsync(stream); return(stream); }
public async Task <File> GetFileAsync(string id) { await AuthenticationAsync(); FilesResource.GetRequest request = Service.Files.Get(id); var model = request.Execute(); return(model); }
public async Task <bool> DownloadFile(string Id, string file) { FileStream downloadedFile = new FileStream(file, FileMode.Create); FilesResource.GetRequest getRequest = service.Files.Get(Id); await getRequest.DownloadAsync(downloadedFile); downloadedFile.Close(); return(true); }
/// <summary> /// Return a DriveData.File using the specified id. /// </summary> /// <param name="id"></param> /// <returns></returns> private DriveData.File GetDriveFile(string id) { // TODO Matt: We don't need to create a new service just for this request. Please pass that service as parameter and use it here. DriveService service = GetService(); FilesResource.GetRequest request = service.Files.Get(id); // TO MATT: Verify: We have to specify the fields we want to get. // If it does not work please reopen the issue. if it works delete these comments. request.Fields = @"files(id,name,kind,md5Checksum)"; return(request.Execute()); }
// Stolen from: https://stackoverflow.com/a/38750409/1621156 private Google.Apis.Drive.v3.Data.File GetFile(string id) { // Fetch file from drive FilesResource.GetRequest request = service.Files.Get(id); request.Fields = "id, name, parents"; request.SupportsAllDrives = true; request.SupportsTeamDrives = true; var parent = request.Execute(); return(parent); }
public GoogleDriveFileModel GetFile(string fileId) { List <GoogleDriveFileModel> googleDriveFiles = new List <GoogleDriveFileModel>(); DriveService driveService = this.GetGoogleDriveService(); FilesResource.GetRequest request = driveService.Files.Get(fileId); request.Fields = "name,parents"; File file = request.Execute(); return(Mapper.MapFileToGoogleDriveFileModel(file)); }
public String GetFile(String googleDriveFileID) { FilesResource.GetRequest request = this.DriveService.Files.Get(googleDriveFileID); string name = Path.GetTempFileName(); using (FileStream stream = new System.IO.FileStream(name, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { request.Download(stream); } return(name); }
private static void DownloadFile(string fileId, string targetDirectory) { FilesResource.GetRequest request = driveService.Files.Get(fileId); request.Fields = "size,name,id,md5Checksum"; GoogleFile fileinfo = request.Execute(); var stream = new MemoryStream(); IDownloadProgress progress = request.DownloadWithStatus(stream); EditorCoroutineUtility.StartCoroutine(DownloadRoutine(progress, stream, fileId, fileinfo.Name, fileinfo.Size.Value, targetDirectory), Instance); WriteTasks.TryAdd(fileId, false); }
/// <summary> /// Asynchronously downloads the file. /// </summary> /// <returns></returns> /// <exception cref="System.IO.FileNotFoundException"></exception> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > DownloadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); if (string.IsNullOrWhiteSpace(m_fileId)) { throw new FileNotFoundException(); } using (DriveService client = GetClient()) using (Stream stream = new MemoryStream()) { FilesResource.GetRequest request = client.Files.Get(m_fileId); request.Fields = "id, name"; IDownloadProgress response = await request.DownloadAsync(stream).ConfigureAwait(false); if (response.Exception == null) { return(await GetMappedAPIFileAsync(result, stream)); } result.Error = new SerializableAPIError { ErrorMessage = response.Exception.Message }; } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
public Google.Apis.Drive.v2.Data.File GetFileById(string id) { if (id != null) { FilesResource.GetRequest file = _driveService.Files.Get(id); return(file.Execute()); } else { return(new Google.Apis.Drive.v2.Data.File()); } }
private string GetFolderName(string Id) { try { FilesResource.GetRequest getRequest = service.Files.Get(Id); Google.Apis.Drive.v3.Data.File folderName = getRequest.Execute(); return(folderName.Name); } catch { return("Error retrieving folder name"); } }