/// <inheritdoc cref="DownloadFile" /> /// <param name="mimeType"> /// MIME type which is used to get correct extension for file. /// </param> private void ExportFile(string fileId, string saveTo, string mimeType) { using var stream = new MemoryStream(); FilesResource.ExportRequest request = GoogleDriveService.Files.Export(fileId, mimeType); request.MediaDownloader.ProgressChanged += progress => ProgressChanged_Callback(progress, stream, saveTo, mimeType); request.Download(stream); }
//Download file from Google Drive by fileId. public static string DownloadGoogleFile(string fileId) { DriveService service = GetService(); string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/"); FilesResource.GetRequest FileRequest = service.Files.Get(fileId); string FileName = FileRequest.Execute().Name; string FilePath = System.IO.Path.Combine(FolderPath, FileName); MemoryStream stream1 = new MemoryStream(); // Convert Google Document to Word Document FilesResource.ExportRequest request = service.Files.Export(fileId, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // 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. request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); SaveStream(stream1, FilePath); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream1); return(FilePath); }
public void DownloadGoogleDoc(string fileId) { DriveService service = GetService(); MemoryStream stream = new MemoryStream(); FilesResource.GetRequest FileRequest = service.Files.Get(fileId); //string FileName = FileRequest.Execute().Name; string FilePath = HttpContext.Current.Server.MapPath("~/Files/" + fileId + ".docx"); // Convert Google Document to Word Document FilesResource.ExportRequest request = service.Files.Export(fileId, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); SaveStream(stream, FilePath); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream); }
public static bool?GetDataoInit(ref UserCredential credential) { FilesResource.ListRequest listRequest; DriveService service; IList <Google.Apis.Drive.v3.Data.File> files; //Создаем сервис запроса на гугл диск service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "datao", }); //Определяем параметры запроса listRequest = service.Files.List(); listRequest.PageSize = 50; listRequest.Fields = "nextPageToken, files(id, name)"; try { //Лист айдишников файлов files = listRequest.Execute() .Files; } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show("Offline mode"); return(false); } if (files != null && files.Count > 0) { foreach (var file in files) { if (file.Name == "datao.init") { FilesResource.ExportRequest request = null; MemoryStream stream = null; try { //Загружаем с драйва datao.init request = service.Files.Export(file.Id, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); stream = new MemoryStream(); request.Download(stream); } catch (Exception ex) { MessageBox.Show("Произошла ошибка при загрузке datao.init"); return(false); } finally { if (stream != null) { //Сохраняем локально byte[] fileFromServer = stream.ToArray(); try { File.WriteAllBytes(@"..\..\datao.init.xlsx", fileFromServer); } catch (IOException ex) { Debug.WriteLine(ex.Message); MessageBox.Show("Произошла ошибка при записи таблицы на диск\n " + ex.Message); } stream.Close(); //Сохраняем ссылку на текущий datao.init файл, для последующего его удаления DataoID = file.Id; } } return(true); } } } //Если же не нашли datao.init DialogResult dialogResult = MessageBox.Show("Do you want to use our template?\n(Also upload to Drive, if available)", "No datao.init file found!", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { //Процедура закачки var fileMetadata = new Google.Apis.Drive.v3.Data.File(); fileMetadata.Name = "datao.init"; fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet"; FilesResource.CreateMediaUpload _request; //TODO: Путь до локальной таблицы-шаблона using (var _stream = new FileStream("example.init.xlsx", FileMode.Open)) { _request = service.Files.Create( fileMetadata, _stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); _request.Fields = "id"; _request.Upload(); } MessageBox.Show("Успешно!"); //загрузить с диска return(false); } //Закрываем программу в случае отрицательного ответа return(null); }