public string getContentsFromFile(string itemID, string mimetype) { return(new GoogleDriveAPI().getContentsFromFile(itemID, mimetype)); UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); FilesResource.ExportRequest exportRequest = service.Files.Export(itemID, "text/plain"); var result = exportRequest.Execute(); return(result); }
public static async Task <byte[]> DownloadFileToByteArray(string url) { // Create Drive API service. _service = GoogleDriveService; // Attempt download // Iterate through file-list and find the relevant file FilesResource.ListRequest listRequest = _service.Files.List(); listRequest.Fields = "nextPageToken, files(id, name, mimeType, originalFilename, size)"; Google.Apis.Drive.v3.Data.File lobjGoogleFile = null; foreach (var item in listRequest.Execute().Files) { if (url.IndexOf(string.Format("id={0}", item.Id)) > -1) { Console.WriteLine(string.Format("{0}: {1}", item.OriginalFilename, item.MimeType)); lobjGoogleFile = item; break; } } FilesResource.ExportRequest request = _service.Files.Export(lobjGoogleFile.Id, GOOGLE_MYMETYPE_PDF); Console.WriteLine(request.MimeType); using MemoryStream lobjMS = new MemoryStream(); await request.DownloadAsync(lobjMS); // At this point the MemoryStream has a length of zero? lobjMS.Position = 0; return(lobjMS.ToArray()); }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "cred.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } Console.WriteLine("Digite o termo de consulta:"); var searchTerms = Console.ReadLine(); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Q = $"fullText contains '{searchTerms}' and mimeType='application/vnd.google-apps.document'"; listRequest.Fields = "nextPageToken, files(id, name,parents,mimeType,description)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute() .Files; Console.WriteLine("Files:"); if (files != null && files.Count > 0) { foreach (var file in files) { FilesResource.ExportRequest exportRequest = service.Files.Export(file.Id, "text/plain"); var s = exportRequest.ExecuteAsStream(); StreamReader reader = new StreamReader(s); string text = reader.ReadToEnd(); var contentWhereFound = text.IndexOf(searchTerms); var resultText = text.Substring(contentWhereFound, 100); Console.WriteLine("{0} - Trecho encontrado : {1}", file.Name, resultText); } Console.WriteLine("---"); Console.WriteLine("Consulta finalizada."); } else { Console.WriteLine("No files found."); } Console.Read(); }
public string getContentsFromFile(string itemID, string mimetype) { FilesResource.ExportRequest exportRequest = GetDriveServiceInstance().Files.Export(itemID, "text/plain"); var result = exportRequest.Execute(); return(result); }
/// <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); }
private static void UploadFile(DriveService service) { File body = new File(); body.Title = "test image ocr - " + DateTime.Now.ToString(" - yyyyMMdd - HHmmss"); body.Description = "test image ocr - " + DateTime.Now.ToString(" - yyyyMMdd - HHmmss"); //body.MimeType = "application/vnd.ms-excel"; body.MimeType = "image/jpeg"; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes("1.jpg"); MemoryStream stream = new MemoryStream(byteArray); try { //FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet"); FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.photo"); request.Ocr = true; request.OcrLanguage = "vi"; request.Convert = true; request.Upload(); File imgFile = request.ResponseBody; // Copy image and paste as document var textMetadata = new File(); //textMetadata.Name = inputFile.Name; //textMetadata.Parents = new List<string> { folderId }; textMetadata.MimeType = "application/vnd.google-apps.document"; FilesResource.CopyRequest requestCopy = service.Files.Copy(textMetadata, imgFile.Id); requestCopy.Fields = "id"; requestCopy.OcrLanguage = "vi"; var textFile = requestCopy.Execute(); // Now we export document as plain text FilesResource.ExportRequest requestExport = service.Files.Export(textFile.Id, "text/plain"); string output = requestExport.Execute(); // Uncomment the following line to print the File ID. // Console.WriteLine("File ID: " + file.Id); Console.WriteLine(output); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
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 static async Task DownloadFileById(string id, string lstrDownloadFile) { // Create Drive API service. _service = GoogleDriveService; var file = _service.Files.Get(id).Execute(); FilesResource.ExportRequest request = _service.Files.Export(file.Id, GOOGLE_MYMETYPE_PDF); Console.WriteLine(request.MimeType); MemoryStream lobjMS = new MemoryStream(); await request.DownloadAsync(lobjMS); // At this point the MemoryStream has a length of zero? lobjMS.Position = 0; var lobjFS = new System.IO.FileStream(lstrDownloadFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); await lobjMS.CopyToAsync(lobjFS); }
//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 OcrImageInfo goo_ocr_uploadFile(OcrImageInfo ocr) { string file = Path.Combine(PATH_OCR_IMAGE, ocr.FileName); if (File.Exists(file) == false) { ocr.StateOcr = STATE_OCR.OCR_FAIL_MISS_FILE; return(ocr); } DataFile body = new DataFile() { Title = ocr.FileName, Description = ocr.Url, //body.MimeType = "application/vnd.ms-excel"; MimeType = "image/jpeg" }; byte[] byteArray = File.ReadAllBytes(file); using (MemoryStream stream = new MemoryStream(byteArray)) { try { //FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet"); FilesResource.InsertMediaUpload request = gooService.Files.Insert(body, stream, "application/vnd.google-apps.photo"); request.Ocr = true; request.OcrLanguage = "vi"; request.Convert = true; request.Upload(); DataFile imgFile = request.ResponseBody; string fileId = imgFile.Id; // Copy image and paste as document var textMetadata = new DataFile(); //textMetadata.Name = inputFile.Name; //textMetadata.Parents = new List<string> { folderId }; textMetadata.MimeType = "application/vnd.google-apps.document"; FilesResource.CopyRequest requestCopy = gooService.Files.Copy(textMetadata, fileId); requestCopy.Fields = "id"; requestCopy.OcrLanguage = "vi"; var textFile = requestCopy.Execute(); // Now we export document as plain text FilesResource.ExportRequest requestExport = gooService.Files.Export(textFile.Id, "text/plain"); string output = requestExport.Execute(); ocr.TextResult = output; ocr.StateOcr = STATE_OCR.OCR_SUCCESS; writeLogMessage("OK: " + ocr.FileName); if (ocr.WriteToFile) { if (!string.IsNullOrEmpty(ocr.TextResult)) { File.WriteAllText(PATH_OCR_IMAGE + @"log\" + ocr.FileName + ".txt", ocr.TextResult); } } } catch (Exception e) { ocr.TextError = e.Message; ocr.StateOcr = STATE_OCR.OCR_FAIL_THROW_ERROR; } } return(ocr); }
public PdfDocument GetPdfDocuments(List <File> Files) { var outputDoc = new PdfDocument(); var pFor = Parallel.ForEach(Files, file => { FilesResource.ExportRequest request = service.Files.Export(file.Id, "application/pdf"); 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. request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); var n = PdfReader.Open(stream, PdfDocumentOpenMode.Import); var page1 = n.Pages[0]; var cropped = new PdfDocument(); cropped.AddPage(page1); using (var ms = new MemoryStream()) { cropped.Save(ms); cropped.Close(); Docs.Add(new DocWName { Name = file.Name, Doc = stream.ToArray() }); } //outputDoc.AddPage(page1); //var n = new PdfDocument(new PdfReader(stream)); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.DownloadWithStatus(stream); }); Docs = Docs.OrderBy(d => d.Name).ToList(); foreach (var doc in Docs) { using (var ms = new MemoryStream(doc.Doc)) { var d = PdfReader.Open(ms, PdfDocumentOpenMode.Import); outputDoc.AddPage(d.Pages[0]); } } return(outputDoc); }
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); }
static void Main(string[] args) { UserCredential credential; // If modifying these scopes, delete previously saved token.json string[] Scopes = { DriveService.Scope.DriveReadonly }; string ApplicationName = "########"; string fileId = "########"; string path = @"########"; //Include filename & extension i.e. C:\stuff\sheet001.xlsx var jetStream = new System.IO.MemoryStream(); using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); FilesResource.ExportRequest request = new FilesResource.ExportRequest(service, fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); request.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."); using (System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { jetStream.WriteTo(file); } break; } case Google.Apis.Download.DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.DownloadWithStatus(jetStream); }
static async Task GetDriveFile(DriveFile driveFileObject, DriveService driveService, string token, dynamic config, string courseName = "Unknown") { var fileRequest = driveService.Files.Get(driveFileObject.Id); fileRequest.OauthToken = token; var stream = new MemoryStream(); fileRequest.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case Google.Apis.Download.DownloadStatus.Completed: { Console.WriteLine(String.Format("Downloaded {0}.", driveFileObject.Title)); SaveStream(stream, String.Format(@".\output\{0}\{1}", courseName, driveFileObject.Title)); break; } case Google.Apis.Download.DownloadStatus.Failed: { try { var driveFile = fileRequest.Execute(); if (config.exportmimes.ContainsKey(driveFile.MimeType)) { FilesResource.ExportRequest exportRequest = driveService.Files.Export(driveFile.Id, (string)config.exportmimes[driveFile.MimeType]); exportRequest.OauthToken = token; exportRequest.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress exportProgress) => { switch (exportProgress.Status) { case Google.Apis.Download.DownloadStatus.Completed: { Console.WriteLine(String.Format("Downloaded {0}.{1}.", driveFileObject.Title, (string)config.mimeextensions[exportRequest.MimeType])); SaveStream(stream, String.Format(@".\output\{0}\{1}.{2}", courseName, driveFileObject.Title, (string)config.mimeextensions[exportRequest.MimeType])); break; } case Google.Apis.Download.DownloadStatus.Failed: { Console.WriteLine(String.Format("Download failed on file {0}.\n{2}\n{1}", driveFileObject.Title, exportProgress.Exception.Message, progress.Exception.Message)); break; } } }; exportRequest.DownloadAsync(stream); } else { Console.WriteLine(String.Format("Download failed on file {0}.\n{1}", driveFileObject.Title, progress.Exception.Message)); } } catch (Exception e) { Console.WriteLine(String.Format("Download failed on file {0}.\n{1}", driveFileObject.Title, e.Message)); } break; } } }; // Synchronous for now await fileRequest.DownloadAsync(stream); }