public static void Upload(string source, string dest) { if (!inited) { return; } var body = new Google.Apis.Drive.v3.Data.File(); body.Name = dest; body.MimeType = getMimeType(source); body.Parents = new List <string>() { createDirectory("sdfsd").Id }; byte[] byteArray = File.ReadAllBytes(source); MemoryStream stream = new MemoryStream(byteArray); FilesResource.CreateMediaUpload request = driveService.Files.Create(body, stream, body.MimeType); if (request.Upload().Exception != null) { Logger.Log(Logger.Module.Core, Logger.Type.Error, request.Upload().Exception.Message); } else { Logger.Log(Logger.Module.Core, Logger.Type.Debug, $"File '{Path.GetFileName(source)}' successfully uploaded"); } }
/// <summary> /// Сохраняет в облаке файл /// </summary> /// <param name="fileId">Id файла</param> /// <param name="folderId">Id папки</param> /// <param name="localFilePath">Файл на диске который нужно залить</param> /// <returns></returns> public bool UploadFile(string localFilePath) { if (Service == null) { return(false); } byte[] byteArray = File.ReadAllBytes(localFilePath); MemoryStream mStream = new MemoryStream(byteArray); // Файл для записи Google.Apis.Drive.v3.Data.File file = new Google.Apis.Drive.v3.Data.File() { Name = "TizTabooDataFile", MimeType = "application/octet-stream", Description = "Файл данных программы TizTaboo", }; // Проверяем существует наш файл в облаке, если нет - создаем if (!FileExists()) { file.Parents = new List <string> { CreateFolder("TizTabooData") }; FilesResource.CreateMediaUpload createRequest = Service.Files.Create(file, mStream, file.MimeType); if (createRequest.Upload().Exception != null) { Log.Error(createRequest.Upload().Exception.Message); return(false); } else { fileId = createRequest.ResponseBody.Id; return(true); } } // Если есть, обновляем else { FilesResource.UpdateMediaUpload updateRequest = Service.Files.Update(file, fileId, mStream, file.MimeType); if (updateRequest.Upload().Exception != null) { Log.Error(updateRequest.Upload().Exception.Message); return(false); } else { return(true); } } }
/// <summary> /// Загрузка файла на Google /// </summary> /// <param name="service">Сервис</param> /// <param name="localfilePath">Локальный путь к файлу</param> /// <param name="parentGoogleDriveId">Идентификатор папки в Google Drive</param> /// <returns></returns> public File UploadFileByParentId(DriveService service, string localfilePath, string parentGoogleDriveId) { if (!System.IO.File.Exists(localfilePath)) { throw new Exception($"File '{localfilePath}' does not exist and can not be uploaded to Google Drive"); } string mimeType = GetMimeType(localfilePath); File body = new File { Name = Path.GetFileName(localfilePath), Description = "Created by ScanImage", MimeType = mimeType }; if (!string.IsNullOrEmpty(parentGoogleDriveId)) { body.Parents = new List <string> { parentGoogleDriveId } } ; byte[] byteArray = System.IO.File.ReadAllBytes(localfilePath); using (MemoryStream stream = new MemoryStream(byteArray)) { FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, mimeType); request.Upload(); return(request.ResponseBody); } }
public Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile) { if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.Description = "Assignment"; byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, ""); request.SupportsTeamDrives = true; request.Upload(); return(request.ResponseBody); } catch (Exception) { return(null); } } else { return(null); } }
public AttemptResult CreateStreamToFile(string name, string parent_id, string mime_type, Stream stream, out string id, out string hash, out DateTime last_write_time) { FilesResource.CreateMediaUpload request = drive_service.Files.Create( new Google.Apis.Drive.v3.Data.File() { Name = name, Parents = new string[] { parent_id } }, stream, mime_type ); request.Fields = "id, name, md5Checksum, modifiedTime, parents"; try { request.Upload(); id = request.ResponseBody.Id; hash = request.ResponseBody.Md5Checksum; last_write_time = request.ResponseBody.ModifiedTime.Solidify(); } catch (Google.GoogleApiException exception) { id = null; hash = null; last_write_time = default(DateTime); return(exception.Error.GetAttemptResult()); } return(AttemptResult.Succeeded); }
/** * The function will take in the file and the parent directory in which you want the file to be in within the * google drive and upload it. The mime and other mota data is collected using the private function * GetMimeType(string fileName). * * @param _service The initialized google drive service that will be querired. * @param _uploadFile The file you wish to upload to the google drive. * @param _parent The parent dierctory that the file should be placed in within the google drive. * @param _descrp each file being uploaded needs a description. This is filled in by default. * @return Return the response message from the server. */ public File UploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Updated APK for Lesion Scanner") { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Name = Path.GetFileName(_uploadFile); body.Description = _descrp; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List <string> { _parent }; byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile)); request.SupportsTeamDrives = true; // You can bind event handler with progress changed event and response recieved(completed event) request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine(e.Message, "Error Occured"); return(null); } } else { Console.WriteLine("The file does not exist.", "404"); return(null); } }
public static Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "") { if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.Description = _descrp; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List<string> { _parent };// UN comment if you want to upload to a folder(ID of parent folder need to be send as paramter in above method) byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile)); request.SupportsTeamDrives = true; request.Upload(); return request.ResponseBody; } catch (Exception e) { Console.WriteLine(e.Message, "Error Occured"); return null; } } else { Console.WriteLine("The file does not exist.", "404"); return null; } }
/// <summary> /// Uploads a file to Google Drive under a specific folder, if parent is specified. /// </summary> /// <param name="_service"></param> /// <param name="_uploadFile"></param> /// <param name="_parent"></param> /// <returns></returns> private Google.Apis.Drive.v3.Data.File UploadToGoogleDrive(DriveService _service, string _uploadFile, string _parent) { if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.MimeType = "text/plain"; body.Parents = new List <string> { _parent }; byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, "text/plain"); request.SupportsTeamDrives = true; // You can bind event handler with progress changed event and response recieved(completed event) request.Upload(); return(request.ResponseBody); } catch (Exception e) { MessageBox.Show(e.Message, "Error Occured"); return(null); } } else { MessageBox.Show("The file does not exist.", "404"); return(null); } }
public override bool Write(string fileName, byte[] data) { try { if ((!FileExists(fileName)) || Overwrite) { string contentType = "image/jpeg"; using (MemoryStream memoryStream = new MemoryStream(data)) { Google.Apis.Drive.v3.Data.File file = new Google.Apis.Drive.v3.Data.File() { Name = fileName }; FilesResource.CreateMediaUpload request = GoogleDriveService.Files.Create(file, memoryStream, contentType); request.Fields = "id"; request.Upload(); } } } catch { return(false); } return(true); }
//file Upload to the Google Drive. public static string FileUploadInFolder(string folderId, HttpPostedFileBase file) { FilesResource.CreateMediaUpload request = null; if (file != null && file.ContentLength > 0) { Google.Apis.Drive.v3.DriveService service = GetService(); string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"), Path.GetFileName(file.FileName)); file.SaveAs(path); var FileMetaData = new Google.Apis.Drive.v3.Data.File() { Name = Path.GetFileName(file.FileName), MimeType = MimeMapping.GetMimeMapping(path), Parents = new List <string> { folderId } }; using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open)) { request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType); request.Fields = "id"; request.Upload(); } } return(request.ResponseBody.Id.ToString()); }
private static void CreateFile(DriveService driveService, string targetFolderId, string targetName, string sourcePath, string contentType) { File fileMetadata = new File { Name = targetName, Parents = new List <string> { targetFolderId } }; string?uploadedFileId = null; using FileStream fs = System.IO.File.OpenRead(sourcePath); FilesResource.CreateMediaUpload createRequest = driveService.Files.Create(fileMetadata, fs, contentType); createRequest.Fields = "id, parents"; createRequest.ProgressChanged += progress => Console.WriteLine($"Upload status: {progress.Status} Bytes sent: {progress.BytesSent}"); createRequest.ResponseReceived += file => { uploadedFileId = file.Id; Console.WriteLine($"Created: {file.Id} parents: {file.Parents}"); }; var uploadProgress = createRequest.Upload(); Console.WriteLine($"Final status: {uploadProgress.Status} {uploadedFileId}"); }
// chunkSize is in MB! public Task UploadFile(Stream stream, string filename, int chunkSize) { File body = new File { Name = Path.GetFileName(filename), MimeType = "application/unknown" }; try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, body.MimeType); if (chunkSize != 0) { request.ChunkSize = chunkSize * 4 * Google.Apis.Upload.ResumableUpload.MinimumChunkSize; } request.Upload(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } Console.WriteLine("Done uploading"); return(Task.FromResult(0)); }
private File CreateNewFile(string filename, string content, string directoryId) { File body = new File(); body.Name = filename; body.Parents = new List <string>() { directoryId }; // File's content. var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(content)); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, String.Empty); request.Fields = "id,modifiedTime,name,version"; request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } }
/// <summary> /// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// </summary> /// <param name="service">a Valid authenticated DriveService</param> /// <param name="uploadFile">path to the file to upload</param> /// <param name="parent"> /// Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder. /// </param> /// <returns> /// If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null /// </returns> public static File UploadFile(DriveService service, string uploadFile, string content, string parent) { File body = new File(); body.Name = System.IO.Path.GetFileName(uploadFile); body.Description = "Test File 1"; body.Parents = new List <string>() { parent }; // File's content. var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(content ?? "")); try { FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, String.Empty); request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } }
private static void UploadFile(string fileName, List <string> parents, string _descrp = "Uploaded with .NET!") { if (System.IO.File.Exists(fileName)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(fileName); body.Description = _descrp; body.MimeType = GetMimeType(fileName); body.Parents = parents; byte[] byteArray = System.IO.File.ReadAllBytes(fileName); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(fileName)); request.Upload(); var winik = request.ResponseBody; } catch (Exception e) { var a = e.Message; } } else { var b = "nie ma pliku"; } }
public static string SaveImage(Stream image, string name) { try { const string Type = "image/jpeg"; string folderId = WebConfigurationManager.AppSettings["GoogleDriveFolderId"]; Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File { Name = name, MimeType = Type, Parents = new List <string> { folderId } }; UserCredential credential = GetCredentials(); DriveService service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = WebConfigurationManager.AppSettings["GoogleDriveApplicationName"] }); FilesResource.CreateMediaUpload request = service.Files.Create(fileMetadata, image, Type); request.Fields = "id"; request.Upload(); Google.Apis.Drive.v3.Data.File file = request.ResponseBody; string googleDriveUrl = "https://drive.google.com/uc?id=" + file.Id + "&export=stream"; return(googleDriveUrl); } catch (Exception exception) { LogException(exception, new Dictionary <string, string>(), ErrorSource.ServiceHelper); return(String.Empty); } }
public Google.Apis.Drive.v3.Data.File UploadFile(string uploadFilePath, string description) { if (File.Exists(uploadFilePath)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); string mimeType = GetMimeType(uploadFilePath); body.Name = Path.GetFileName(uploadFilePath); body.Description = description; body.MimeType = mimeType; byte[] byteArray = System.IO.File.ReadAllBytes(uploadFilePath); MemoryStream stream = new MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = Service.Files.Create(body, stream, mimeType); request.SupportsTeamDrives = true; request.Upload(); return(request.ResponseBody); } catch { return(new Google.Apis.Drive.v3.Data.File()); } } else { return(new Google.Apis.Drive.v3.Data.File()); } }
/// /// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// /// a Valid authenticated DriveService /// path to the file to upload /// Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder. /// If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null public static File UploadFile(DriveService _service, string _uploadFile, string _parent) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.Description = "File uploaded by FileSync"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List <string> { _parent }; body.WritersCanShare = true; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile)); request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } } else { Console.WriteLine("File does not exist: " + _uploadFile); return(null); } }
// Calling webservice Google.Apis.Drive.v3 public Google.Apis.Drive.v3.Data.File FileUploadtoGD(DriveService objService, string strUploadFile, string strDescription = "Uploaded with .NET!") { if (System.IO.File.Exists(strUploadFile)) { string strMIMEType = GetMIMEType(strUploadFile); Google.Apis.Drive.v3.Data.File objFileBody = new Google.Apis.Drive.v3.Data.File(); objFileBody.Name = System.IO.Path.GetFileName(strUploadFile); objFileBody.Description = strDescription; objFileBody.MimeType = strMIMEType; byte[] byteArray = System.IO.File.ReadAllBytes(strUploadFile); System.IO.MemoryStream objStream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload objFileUpload = objService.Files.Create(objFileBody, objStream, strMIMEType); objFileUpload.SupportsTeamDrives = true; objFileUpload.Upload(); return(objFileUpload.ResponseBody); } catch (Exception e) { { MessageBox.Show(e.Message, "Error Occured"); return(null); } } } else { MessageBox.Show("The file does not exist.", "404"); return(null); } }
static void Main(string[] args) { UserCredential credential; string filePath1 = "C:/Users/Sorin/Desktop/Orar.txt"; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { 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.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name)"; 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) { Console.WriteLine("{0} ({1})", file.Name, file.Id); } } else { Console.WriteLine("No files found."); } Console.Read(); if (System.IO.File.Exists(filePath1)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(filePath1); byte[] byteArray = System.IO.File.ReadAllBytes(filePath1); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, filePath1); request.SupportsTeamDrives = true; request.Upload(); } else { System.Console.WriteLine("The file does not exist."); } }
public Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!") { if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.Description = _descrp; body.MimeType = GetMimeType(_uploadFile); byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile)); request.SupportsTeamDrives = true; request.ProgressChanged += Request_ProgressChanged; request.ResponseReceived += Request_ResponseReceived; request.Upload(); return(request.ResponseBody); } catch (Exception e) { MessageBox.Show(e.Message, "Error Occured"); return(null); } } else { MessageBox.Show("The file does not exist."); return(null); } }
/// <summary> /// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// </summary> /// <param name="_service">a Valid authenticated DriveService</param> /// <param name="_uploadFile">path to the file to upload</param> /// <param name="_parent">Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder.</param> /// <returns>If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null</returns> public static File uploadFile(DriveService _service, string _uploadFile, string _parent) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.Description = "File uploaded by Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); //body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile)); //request.Convert = true; // uncomment this line if you want files to be converted to Drive format request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } } else { Console.WriteLine("File does not exist: " + _uploadFile); return(null); } }
public Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!") { if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.Description = _descrp; body.MimeType = "image/jpeg";//GetMimeType(_uploadFile); // body.Parents = new List<string> { _parent };// UN comment if you want to upload to a folder(ID of parent folder need to be send as paramter in above method) byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, "image/jpeg");//GetMimeType(_uploadFile) request.SupportsTeamDrives = true; // You can bind event handler with progress changed event and response recieved(completed event) request.ProgressChanged += Request_ProgressChanged; request.ResponseReceived += Request_ResponseReceived; request.Upload(); return(request.ResponseBody); } catch (Exception e) { //MessageBox.Show(e.Message, "Error Occured"); return(null); } } else { //MessageBox.Show("The file does not exist.", "404"); return(null); } }
/// <summary> /// Upload a new file to Google Drive /// </summary> /// <param name="service">DriveService</param> /// <param name="description">File description</param> /// <param name="fileName">File name</param> /// <param name="contentType">File content type</param> /// <param name="filepath">Full path of the current database file</param> /// <returns>Return status of the upload</returns> private string uploadFile(DriveService service, string description, string fileName, string contentType, string filePath) { File temp = new File(); if (string.IsNullOrEmpty(fileName)) { temp.Name = System.IO.Path.GetFileName(filePath); } else { temp.Name = fileName; } temp.Description = description; temp.MimeType = contentType; byte[] byteArray = System.IO.File.ReadAllBytes(filePath); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.CreateMediaUpload request = service.Files.Create(temp, stream, contentType); IUploadProgress progress = request.Upload(); if (progress.Exception != null) { throw progress.Exception; } File file = request.ResponseBody; return(string.Format("Google Drive 文件已更新,文件名:{0},ID:{1}", file.Name, file.Id)); }
public static File createFile(DriveService _service, string _name, string _description, string _parent, MarkedFileData markedFile) { File NewFile = null; // Create metaData for a new Directory var fileMetadata = new File() { Name = _name, Parents = new List <string>() { _parent }, //MimeType = "application/vnd.google-apps.folder", Description = _description }; try { using System.IO.StreamReader reader = new System.IO.StreamReader(markedFile.fullPath); FilesResource.CreateMediaUpload request = _service.Files.Create(fileMetadata, reader.BaseStream, GetMimeType(markedFile.fullPath)); request.Fields = "id"; request.Upload(); NewFile = request.ResponseBody; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } return(NewFile); }
internal bool UploadFile(string name, string mimeType, string parentId, Stream fileStream, IProgress <long> progress, Func <int, bool> shouldAbort) { var fileMetadata = new File { Name = name, MimeType = mimeType, Parents = new List <string> { parentId } }; FilesResource.CreateMediaUpload request = _driveService.Files.Create(fileMetadata, fileStream, fileMetadata.MimeType); request.Fields = "id"; if (progress != null) { request.ProgressChanged += u => progress.Report(u.BytesSent); } IUploadProgress uploadProgress = request.Upload(); int currentTry = 0; while (uploadProgress.Status != UploadStatus.Completed) { if (!shouldAbort(currentTry)) { return(false); } ++currentTry; request.Resume(); } return(true); }
public static File createFile(DriveService _service, string _title, string _description, string _parent, byte[] bytes) { var watchi = System.Diagnostics.Stopwatch.StartNew(); File NewFile = null; File body = new File(); body.Name = _title; body.Description = _description; body.Parents = new List <string>() { _parent }; try { System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes); FilesResource.CreateMediaUpload req = _service.Files.Create(body, stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); req.Upload(); NewFile = req.ResponseBody; } catch (Exception e) { MessageBox.Show(e.Message, "Error Occured2"); } var elapsedMs = watchi.ElapsedMilliseconds; Console.WriteLine("time create file = " + elapsedMs / 1000 + " sec " + elapsedMs % 1000 + "msec"); return(NewFile); }
// https://stackoverflow.com/questions/45663027/resuming-interrupted-upload-using-google-drive-v3-c-sharp-sdk private string Test(Stream stream, string parent, string name, string originalFileName, string mimeType) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = name; body.OriginalFilename = originalFileName; body.Parents = new List <string>() { parent }; body.MimeType = mimeType; FilesResource.CreateMediaUpload createRequest = Service.Files.Create(body, stream, mimeType); Google.Apis.Upload.IUploadProgress progress = createRequest.Upload(); //createRequest.ContentStream if (progress.Status == Google.Apis.Upload.UploadStatus.Uploading) { // stream 이 seekable "해야할듯.. } //createRequest. //createRequest.Resume() //Google.Apis.Upload.IUploadProgress progress = createRequest.Upload(); //Google.Apis.Drive.v3.Data.File response = createRequest.ResponseBody; //return response.Id; return(""); }
/// <summary> /// This is manual approach for creating Fr8 trigger for some document, mainly used as backup plan for automatic apps script run /// </summary> /// <param name="authDTO"></param> /// <param name="formId"></param> /// <param name="desription"></param> /// <returns></returns> public async Task <string> CreateManualFr8TriggerForDocument(GoogleAuthDTO authDTO, string formId, string desription = "Script uploaded from Fr8 application") { string response = ""; try { var driveService = await _googleDrive.CreateDriveService(authDTO); var formFilename = FormFilename(driveService, formId); Google.Apis.Drive.v3.Data.File scriptFile = new Google.Apis.Drive.v3.Data.File(); scriptFile.Name = "Script for: " + formFilename; scriptFile.Description = desription; scriptFile.MimeType = "application/vnd.google-apps.script+json"; // Create a memory stream using (MemoryStream memoryStream = new MemoryStream()) { //load template file and replace specific formID var assembly = Assembly.GetExecutingAssembly(); var resourceName = "terminalGoogle.Template.googleAppScriptFormResponse.json"; string content; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { content = reader.ReadToEnd(); } content = content.Replace("@ID", formId); content = content.Replace("@ENDPOINT", CloudConfigurationManager.GetSetting("GoogleFormEventWebServerUrl")); byte[] contentAsBytes = Encoding.UTF8.GetBytes(content); memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length); // Set the position to the beginning of the stream. memoryStream.Seek(0, SeekOrigin.Begin); //upload file to google drive string existingFileLink = ""; if (!_googleDrive.FileExist(driveService, scriptFile.Name, out existingFileLink)) { FilesResource.CreateMediaUpload request = driveService.Files.Create(scriptFile, memoryStream, "application/vnd.google-apps.script+json"); request.Upload(); response = request.ResponseBody.WebViewLink; } else { response = existingFileLink; } } } catch (Exception e) { throw new Exception(e.Message); } return(await Task.FromResult(response)); }
public static bool UploadFile(DriveService _service, string _uploadFile) { if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.MimeType = MimeMapping.GetMimeMapping(_uploadFile); // note: convert to bytes if direct reading of database backup file does not work //byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); //using (var stream = new System.IO.MemoryStream(byteArray)) using (var stream = new System.IO.FileStream(_uploadFile, System.IO.FileMode.Open)) { try { //TODO: Create a logging mechanism and insert the error message (exception) in it FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, body.MimeType); request.SupportsAllDrives = true; //note: below code can be used to show upload progression bar // You can bind event handler with progress changed event and response recieved(completed event) //request.ProgressChanged += Request_ProgressChanged; //request.ResponseReceived += Request_ResponseReceived; var result = request.Upload(); if (result.Status == UploadStatus.Completed) { return(true); } if (result.Status != UploadStatus.Completed || request == null || request.ResponseBody == null) //check status, now it's throwing here sometimes { return(false); } //if (request == null) // throw new Exception("Error! Sending The Request"); //if (request.ResponseBody == null) // throw new Exception("Error! Response body is null"); //var fileUploaded = request.ResponseBody; //Npte: A link for downloading a file in the browser if we use WebContentLink //return fileUploaded.WebContentLink; return(false); } catch (Exception ex) { //MessageBox.Show(ex.Message, "Error While Uploading The Database Backup To GoogleDrive"); return(false); } } } else { //MessageBox.Show("The file does not exist."); return(false); } }