Пример #1
0
        private void btnRevertSelected_Click(object sender, EventArgs e)
        {
            foreach (Object item in lstResults.SelectedItems)
            {
                RestoreFileItem file = (RestoreFileItem)item;
                Console.WriteLine("Starting restore of... " + file.current_name);

                // Do restore
                string fileCachePath = downloadPath + "\\cache\\" + file.fileId + ".bin";

                Google.Apis.Drive.v3.Data.File f = service.Files.Get(file.fileId).Execute();

                //Download Revision
                MemoryStream stream = new MemoryStream();
                RevisionsResource.GetRequest dlRevision = new RevisionsResource.GetRequest(service, file.fileId, file.previous_revisionId);
                dlRevision.Download(stream);
                //service.Files.Get(revision.Id).Download(stream);
                System.IO.File.WriteAllBytes(fileCachePath, stream.ToArray());

                //Replace revision
                //System.IO.FileStream fs = new FileStream(downloadPath + "\\download\\"+ revision.OriginalFilename, FileMode.Open);
                FilesResource.UpdateMediaUpload fUpload = service.Files.Update(f, file.fileId, stream, file.current_mimeType);
                f.Name         = file.previous_name;
                f.Id           = null;
                fUpload.Fields = "name";
                var uploadStatus = fUpload.Upload();

                if (uploadStatus.Exception != null)
                {
                    MessageBox.Show("Error Uploading File!");
                }
            }
        }
Пример #2
0
        public static File updateFile(DriveService _service, string _uploadFile, string _fileId)
        {
            if (System.IO.File.Exists(_uploadFile))
            {
                File body = new File();
                body.Name        = System.IO.Path.GetFileName(_uploadFile);
                body.Description = "File updated by Diamto Drive Sample";
                body.MimeType    = GetMimeType(_uploadFile);

                byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                try
                {
                    FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, stream, GetMimeType(_uploadFile));
                    var result = request.Upload();
                    if (result.Status == Google.Apis.Upload.UploadStatus.Failed)
                    {
                        throw new Exception(result.Exception.Message);
                    }

                    return(request.ResponseBody);
                }
                catch (Exception e)
                {
                    MessageBox.Show("An error occurred: " + e.Message);
                    return(null);
                }
            }
            else
            {
                MessageBox.Show("File does not exist: " + _uploadFile);
                return(null);
            }
        }
Пример #3
0
        internal static File UpdateFile(DriveService service, string uploadFile, string parent, string fileId)
        {
            if (System.IO.File.Exists(uploadFile))
            {
                File body = new File();
                body.Title    = System.IO.Path.GetFileName(uploadFile);
                body.MimeType = "application/unknown";
                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);

                FilesResource.UpdateMediaUpload request = service.Files.Update(body, fileId, stream, body.MimeType);
                request.Upload();
                return(request.ResponseBody);
            }
            else
            {
                Console.WriteLine("File does not exist: " + uploadFile);
                return(null);
            }
        }
Пример #4
0
        /// <summary>
        /// Updates a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/update
        /// </summary>
        /// <param name="service">a Valid authenticated DriveService</param>
        /// <param name="uploadFile">path to the file to upload</param>
        /// <param name="parentIdFolder">Collection of parent folders which contain this file.
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <param name="idFile">the resource id for the file we would like to update</param>
        /// <returns>If upload succeeded returns the File resource of the uploaded file
        ///          If the upload fails returns null</returns>
        public static File UpdateFile(DriveService service, string uploadFile, string parentIdFolder, string idFile)
        {
            if (System.IO.File.Exists(uploadFile))
            {
                File body = new File
                {
                    Title       = Path.GetFileName(uploadFile),
                    Description = "File updated Drive",
                    MimeType    = GetMimeType(uploadFile),
                    Parents     = new List <ParentReference> {
                        new ParentReference {
                            Id = parentIdFolder
                        }
                    }
                };

                // File's content.
                byte[]       byteArray = System.IO.File.ReadAllBytes(uploadFile);
                MemoryStream stream    = new MemoryStream(byteArray);
                try
                {
                    FilesResource.UpdateMediaUpload request = service.Files.Update(body, idFile, stream, GetMimeType(uploadFile));
                    request.Upload();
                    return(request.ResponseBody);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return(null);
        }
Пример #5
0
        /// <summary>
        /// Updates a file with news params
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="newTitle"></param>
        /// <param name="newDescription"></param>
        /// <param name="newMimeType"></param>
        /// <param name="newFilename"></param>
        /// <param name="newRevision"></param>
        /// <returns></returns>
        private static Boolean updateFile(DriveService service, String fileId, String newTitle, String newDescription, String newMimeType, String newFilename, bool newRevision)
        {
            try
            {
                // First retrieve the file from the API.
                Google.Apis.Drive.v3.Data.File file = service.Files.Get(fileId).Execute();

                // File's new metadata.
                file.Name        = newTitle;
                file.Description = newDescription;
                file.MimeType    = newMimeType;

                // File's new content.
                byte[] byteArray = System.IO.File.ReadAllBytes(newFilename);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                // Send the request to the API.
                FilesResource.UpdateMediaUpload request = service.Files.Update(file, fileId, stream, newMimeType);
                request.Upload();

                //Google.Apis.Drive.v3.Data.File updatedFile = request.ResponseBody;
                //return updatedFile;
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return(false);
            }
        }
Пример #6
0
        private static File updateFile(String fileId, String newTitle, String newDescription, String newMimeType, String filepath, bool newRevision)
        {
            try
            {
                // First retrieve the file from the API.
                File file = service.Files.Get(fileId).Fetch();

                // File's new metadata.
                file.Title       = newTitle;
                file.Description = newDescription;
                file.MimeType    = newMimeType;

                // File's new content.
                byte[] byteArray = System.IO.File.ReadAllBytes(filepath);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                // Send the request to the API.
                FilesResource.UpdateMediaUpload request = service.Files.Update(file, fileId, stream, newMimeType);
                request.NewRevision = newRevision;
                request.Upload();

                File updatedFile = request.ResponseBody;
                return(updatedFile);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return(null);
            }
        }
Пример #7
0
        /// <summary>
        /// 更新已經存在的檔案
        /// </summary>
        /// <param name="_service"></param>
        /// <param name="_uploadFile"></param>
        /// <param name="_fileId"></param>
        /// <returns></returns>
        public static GData.File updateFile(DriveService _service, string _uploadFile, string _fileId)
        {
            if (System.IO.File.Exists(_uploadFile))
            {
                GData.File body = new GData.File();
                body.Name        = System.IO.Path.GetFileName(_uploadFile);
                body.Description = "File updated by Diamto Drive Sample";
                body.MimeType    = GetMimeType(_uploadFile);

                byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                try
                {
                    FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, 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);
            }
        }
        /// <summary>
        /// Updates a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/update
        /// </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>
        /// <param name="_fileId">the resource id for the file we would like to update</param>                      
        /// <returns>If upload succeeded returns the File resource of the uploaded file 
        ///          If the upload fails returns null</returns>
        public static File updateFile(DriveService _service, string _uploadFile, string _parent,string _fileId)
        {

            if (System.IO.File.Exists(_uploadFile))
            {
                File body = new File();
                body.Title = System.IO.Path.GetFileName(_uploadFile);
                body.Description = "File updated 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.UpdateMediaUpload request = _service.Files.Update(body, _fileId, 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;
            }

        }
        public static async Task <bool> UploadGoogleFile(string fileName, string fileId)
        {
            if (!System.IO.File.Exists(fileName) || !Storage.xs.Settings.IsGDriveOn())
            {
                return(false);
            }

            byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

            try
            {
                File body = new File();
                FilesResource.UpdateMediaUpload req = _service.Files.Update(body, fileId, stream, "application/json");
                var progress = await req.UploadAsync();

                File response = req.ResponseBody;
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Пример #10
0
        /// <summary>
        /// Update an existing file's metadata and content.
        /// </summary>
        /// <param name="service">Drive API service instance.</param>
        /// <param name="fileId">ID of the file to update.</param>
        /// <param name="newTitle">New title for the file.</param>
        /// <param name="newDescription">New description for the file.</param>
        /// <param name="newMimeType">New MIME type for the file.</param>
        /// <param name="newFilename">Filename of the new content to upload.</param>
        /// <param name="newRevision">Whether or not to create a new revision for this file.</param>
        /// <returns>Updated file metadata, null is returned if an API error occurred.</returns>
        public static Google.Apis.Drive.v2.Data.File updateFile(String fileId, String newTitle, String newContent, String newFilename, bool newRevision)
        {
            try
            {
                // First retrieve the file from the API.
                Google.Apis.Drive.v2.Data.File file = service.Files.Get(fileId).Execute();

                // File's new metadata.
                file.Title = newTitle;

                // File's new content.
                //byte[] byteArray = System.IO.File.ReadAllBytes(newFilename);
                byte[] byteArray = System.Text.Encoding.Unicode.GetBytes(newContent);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                // Send the request to the API.
                FilesResource.UpdateMediaUpload request = service.Files.Update(file, fileId, stream, file.MimeType);
                request.NewRevision = newRevision;
                request.Upload();

                currentJobFile = request.ResponseBody;
                return(currentJobFile);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return(null);
            }
        }
Пример #11
0
        public static File updateFile(DriveService _service, string text, string _fileName, string _parent = null)
        {
            string       Q_doc  = "title = '" + _fileName + "' and mimeType = 'application/vnd.google-apps.document'";
            IList <File> _Files = GetFiles(_service, Q_doc);

            File body = new File();

            body.Title       = _Files[0].Title; // заголовок
            body.Description = "File updated by Diamto Drive Sample";
            body.MimeType    = "text/html";     //задать тип файла
            // body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } }; родителя не меняем

            byte[] byteArray = Encoding.UTF8.GetBytes(text);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
            try
            {
                string _fileId = _Files[0].Id;
                FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, stream, "text/html");
                request.Upload();
                request.Convert = true;
                return(request.ResponseBody);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Пример #12
0
        //--------------------------------------------------------------------------------------------------
        public static async Task <Google.Apis.Drive.v3.Data.File> UpdateFileAsync(string fileId, Stream stream, string mimeType = "application/octet-stream")
        {
            Google.Apis.Drive.v3.Data.File  body = new Google.Apis.Drive.v3.Data.File();
            FilesResource.UpdateMediaUpload req  = Service.Files.Update(body, fileId, stream, mimeType);
            //req.KeepRevisionForever = true;
            await req.UploadAsync();

            return(req.ResponseBody);
        }
Пример #13
0
 public async Task UploadFileAsync(string fileId, Stream stream, Google.Apis.Drive.v3.Data.File file = null)
 {
     if (file == null)
     {
         file = new Google.Apis.Drive.v3.Data.File();
     }
     FilesResource.UpdateMediaUpload updateMediaUpload = service.Files.Update(file, fileId, stream, file.MimeType);
     await updateMediaUpload.UploadAsync();
 }
Пример #14
0
        public GoogleDriveFile UpdateFile(
            string uploadFile,
            string fileId,
            String description = "File updated by DriveUploader for Windows",
            byte[] byteArray   = null)
        {
            if (System.IO.File.Exists(uploadFile))
            {
                String directoryId = GetParentId();
                var    body        = new File
                {
                    Title       = System.IO.Path.GetFileName(uploadFile),
                    Description = description,
                    MimeType    = GetMimeType(uploadFile),
                    Parents     = new List <ParentReference>()
                    {
                        new ParentReference()
                        {
                            Id = directoryId
                        }
                    }
                };

                // File's content.
                // byte[] byteArray = System.IO.File.ReadAllBytes(uploadFile);
                var stream = new System.IO.MemoryStream(byteArray);
                try
                {
                    FilesResource.UpdateMediaUpload request = Service.Files.Update(body, fileId, stream, GetMimeType(uploadFile));
                    request.Upload();
                    var file = request.ResponseBody;
                    if (file == null)
                    {
                        throw new Exception("InsertMediaUpload request.ResponseBody is null");
                    }
                    else
                    {
                        return(ConvertFileToGoogleDriveFile(file));
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred: " + e.Message, e);
                    return(null);
                }
            }
            else
            {
                Logger.Error("File does not exist: " + uploadFile);
                return(null);
            }
        }
Пример #15
0
        /// <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);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Upload method.
        /// </summary>
        /// <param name="folder">The folder to upload to.</param>
        /// <param name="filePath">The file path to upload.</param>
        /// <param name="fileId">The file id.</param>
        /// <param name="retry">Indicates whether to retry
        /// upon failure.</param>
        public void Upload(
            string folder, string filePath, string fileId, bool retry)
        {
            if (retry == true)
            {
                TimeSpan timeOut = driveService.HttpClient.Timeout +
                                   TimeSpan.FromSeconds(100);

                // apparentely, we need to reset the drive service
                driveService = new DriveService(initializer);
                driveService.HttpClient.Timeout = timeOut;
            }

            FileInfo file = new (filePath);

            Google.Apis.Drive.v3.Data.File fileMetadata = new ();
            fileMetadata.Name = file.Name;

            using FileStream stream = new (filePath, System.IO.FileMode.Open);

            string mimeType = MimeTypes.GetMimeType(file.Name);

            if (string.IsNullOrWhiteSpace(fileId))
            {
                IList <string> parents = new List <string>();
                parents.Add(folder);
                fileMetadata.Parents = parents;

                FilesResource.CreateMediaUpload request =
                    driveService.Files.Create(fileMetadata, stream, mimeType);

                request.Fields = "id, name, parents";

                request.ProgressChanged  += UploadProgressChanged;
                request.ResponseReceived += UploadResponseReceived;

                request.Upload();
            }
            else
            {
                FilesResource.UpdateMediaUpload request =
                    driveService.Files.Update(
                        fileMetadata, fileId, stream, mimeType);

                request.Fields = "id, name, parents";

                request.ProgressChanged  += UploadProgressChanged;
                request.ResponseReceived += UploadResponseReceived;
                request.Upload();
            }
        }
Пример #17
0
        public async Task Upload(VersionedData data)
        {
            var storageToUpdate = new File {
                Name = (await _remoteStorageInfoRepository.GetRemoteStorageInfo()).Name
            };

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data))))
            {
                FilesResource.UpdateMediaUpload updateRequest =
                    _service.Files.Update(storageToUpdate,
                                          (await _remoteStorageInfoRepository.GetRemoteStorageInfo()).Id, stream, DataFileContentType);
                await updateRequest.UploadAsync();
            }
        }
Пример #18
0
        public static void UpdateFiles(string path)
        {
            string fileName = Path.GetFileName(path);
            string fileId   = GetFileId(fileName);

            File file = new File();

            byte[]       byteArray = System.IO.File.ReadAllBytes(path);
            MemoryStream stream    = new MemoryStream(byteArray);

            FilesResource.UpdateMediaUpload request = Service.Files.Update(file, fileId, stream, mimeType);

            request.Upload();
        }
 /// <summary>
 /// Updates a file on Google Drive: GooglDriveService.Files.Update
 /// Requirements: A Valid authenticated DriveService path to the file to upload
 /// If upload succeeded returns the File resource of the uploaded file
 /// If the upload fails returns null
 /// </summary>
 /// <param name="service"></param>
 /// <param name="uploadFile"></param>
 /// <param name="parentId"></param>
 /// <param name="fileId">The resource id for the file we would like to update</param>
 /// <param name="fileDescription"></param>
 /// <returns></returns>
 public GoogleDriveManagerResult UpdateFile(DriveService service, string uploadFile, string parentId,
                                            string fileId, string fileDescription)
 {
     result = new GoogleDriveManagerResult();
     try
     {
         if (System.IO.File.Exists(uploadFile))
         {
             var mimeType = GoogleDriveMimeService.GetFileMimeType(uploadFile);
             Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File()
             {
                 Name        = System.IO.Path.GetFileName(uploadFile),
                 Description = fileDescription,
                 MimeType    = mimeType,
                 Parents     = new List <string> {
                     parentId
                 }
             };
             byte[]       byteArray = System.IO.File.ReadAllBytes(uploadFile);
             MemoryStream stream    = new MemoryStream(byteArray);
             FilesResource.UpdateMediaUpload request = service.Files.Update(body, fileId, stream, mimeType);
             request.ProgressChanged  += Request_ProgressChanged;
             request.ResponseReceived += Request_ResponseReceived;
             request.Upload();
             Google.Apis.Drive.v3.Data.File response = request.ResponseBody;
             if (response != null)
             {
                 result.GoogleDriveFileId        = response.Id;
                 result.IsGoogleDriveFileUpdated = true;
             }
             else
             {
                 result.IsGoogleDriveFileUpdated = false;
                 result.Errors.Add(GoogleDriveManagementConstants.FileNotUpdatedError);
             }
         }
         else
         {
             result.Errors.Add(GoogleDriveManagementConstants.FileOnDiskDoesNotExistError);
         }
         return(result);
     }
     catch (Exception e)
     {
         WriteToConsole(GoogleDriveManagementConstants.UpdateFileException + e.Message);
         result.Exceptions.Add(e);
         return(result);
     }
 }
Пример #20
0
        /// <summary>
        /// Replace contents of the Google Drive File with currently open Database file
        /// </summary>
        /// <param name="service">DriveService</param>
        /// <param name="file">File from Google Drive</param>
        /// <param name="filePath">Full path of the current database file</param>
        /// <param name="contentType">Content type of the Database file</param>
        /// <returns>Return status of the update</returns>
        private string updateFile(DriveService service, File file, string filePath, string contentType)
        {
            byte[] byteArray = System.IO.File.ReadAllBytes(filePath);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

            File temp = new File();

            FilesResource.UpdateMediaUpload request = service.Files.Update(temp, file.Id, stream, contentType);
            IUploadProgress progress = request.Upload();

            if (progress.Exception != null)
            {
                throw progress.Exception;
            }

            return(string.Format("Google Drive 文件已更新,文件名:{0},ID:{1}", file.Name, file.Id));
        }
Пример #21
0
        public void Update(string fileID, string filePath, string extensionOfLocal, ref bool workError)
        {
            string uploadType = SelectContentType(extensionOfLocal);

            try
            {
                Google.Apis.Drive.v3.Data.File SelectedFile = service.Files.Get(fileID).Execute();
                byte[] byteArray = System.IO.File.ReadAllBytes(filePath);
                System.IO.MemoryStream          stream  = new System.IO.MemoryStream(byteArray);
                FilesResource.UpdateMediaUpload request = service.Files.Update(SelectedFile, fileID, stream, uploadType);
                request.Upload();
            }
            catch (Exception e)
            {
                workError = true;
                MessageBox.Show("Upload Failed: " + e.Message);
            }
        }
        /// <summary>
        /// 更新指定FileID的檔案
        /// </summary>
        /// <param name="fileName">欲上傳至Google Drive並覆蓋在Google Drive上舊版檔案的檔案位置 </param>
        /// <param name="fileId">存在於Google Drive 舊版檔案的FileID </param>
        /// <param name="contentType">MIME Type</param>
        /// <returns>如更新成功,回傳更新後的Google Drive File</returns>
        public Google.Apis.Drive.v2.Data.File UpdateFile(string fileName, string fileId, string contentType)
        {
            CheckCredentialTimeStamp();
            try
            {
                Google.Apis.Drive.v2.Data.File file = _service.Files.Get(fileId).Execute();
                byte[]       byteArray = System.IO.File.ReadAllBytes(fileName);
                MemoryStream stream    = new MemoryStream(byteArray);
                FilesResource.UpdateMediaUpload request = _service.Files.Update(file, fileId, stream, contentType);
                request.NewRevision = true;
                request.Upload();

                Google.Apis.Drive.v2.Data.File updatedFile = request.ResponseBody;
                return(updatedFile);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Пример #23
0
        public File UpdateFile(string _uploadFile, string description, string parent, string _fileId)
        {
            File body = new File();

            body.Name        = System.IO.Path.GetFileName(_uploadFile);
            body.Description = description;
            body.MimeType    = GetMimeType(_uploadFile);
            if (!string.IsNullOrEmpty(parent))
            {
                body.Parents = new List <string> {
                    parent
                };
            }

            // File's content.
            byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
            System.IO.MemoryStream          stream  = new System.IO.MemoryStream(byteArray);
            FilesResource.UpdateMediaUpload request = service.Files.Update(body, _fileId, stream, GetMimeType(_uploadFile));
            request.Upload();
            return(request.ResponseBody);
        }
Пример #24
0
            public AttemptResult UpdateStreamToFile(string id, string mime_type, Stream stream)
            {
                FilesResource.UpdateMediaUpload request = drive_service.Files.Update(
                    new Google.Apis.Drive.v3.Data.File()
                {
                },
                    id,
                    stream,
                    mime_type
                    );

                try
                {
                    request.Upload();
                }
                catch (Google.GoogleApiException exception)
                {
                    return(exception.Error.GetAttemptResult());
                }

                return(AttemptResult.Succeeded);
            }
Пример #25
0
        public async Task <Google.Apis.Drive.v2.Data.File> UpdateFile(string fileName, string fileId, string contentType)//更新指定FileID的檔案
        {
            CheckCredentialTimeStamp();
            try
            {
                Google.Apis.Drive.v2.Data.File file = _service.Files.Get(fileId).Execute();
                StorageFile fileToUpdate            = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

                IRandomAccessStream randomAccessStream = await fileToUpdate.OpenReadAsync();

                Stream stream = randomAccessStream.AsStream();
                FilesResource.UpdateMediaUpload request = _service.Files.Update(file, fileId, stream, contentType);
                request.NewRevision = true;
                request.Upload();
                Google.Apis.Drive.v2.Data.File updatedFile = request.ResponseBody;
                return(updatedFile);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Пример #26
0
        protected override void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            disposed = true;
            base.Dispose(disposing);

            if (written)
            {
                dataStream.Seek(0, SeekOrigin.Begin);

                FilesResource.UpdateMediaUpload request = storage.Service.Files.Update(file, file.Id, dataStream, "application/octet-stream");
                request.NewRevision = storage.UseVersioning;

                request.Upload();
            }

            dataStream.Dispose();
        }
Пример #27
0
        /// <summary>
        /// Update an existing file's metadata and content.
        /// </summary>
        /// <param name="service">Drive API service instance.</param>
        /// <param name="fileId">ID of the file to update.</param>
        /// <param name="newTitle">New title for the file.</param>
        /// <param name="newDescription">New description for the file.</param>
        /// <param name="newMimeType">New MIME type for the file.</param>
        /// <param name="newFilename">Filename of the new content to upload.</param>
        /// <param name="newRevision">Whether or not to create a new revision for this file.</param>
        /// <returns>Updated file metadata, null is returned if an API error occurred.</returns>
        public GoogleDriveFile updateFile(String fileId, String newTitle,
                                          String newDescription, String newMimeType, String newFilename, bool newRevision)
        {
            try
            {
                // First retrieve the file from the API.
                File file = Service.Files.Get(fileId).Execute();

                // File's new metadata.
                file.Name        = newTitle;
                file.Description = newDescription;
                file.MimeType    = newMimeType;

                // File's new content.
                byte[] byteArray = System.IO.File.ReadAllBytes(newFilename);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                // Send the request to the API.
                FilesResource.UpdateMediaUpload request = Service.Files.Update(file, fileId, stream, newMimeType);
                //request.NewRevision = newRevision;
                request.Upload();

                File updatedFile = request.ResponseBody;


                if (updatedFile == null)
                {
                    throw new Exception("InsertMediaUpload request.ResponseBody is null");
                }
                else
                {
                    return(ConvertFileToGoogleDriveFile(file));
                }
            }
            catch (Exception e)
            {
                //Logger.Error(e, "An error occurred: " + e.StackTrace, fileId, newDescription, newFilename, newMimeType, newTitle);
                return(null);
            }
        }
Пример #28
0
        private static string uploadToDrive(string fileToUpload, string parentDriveFolder, string fileId)
        {
            var service = initGoogleAuth();

            Google.Apis.Drive.v3.Data.File fileMetaData = new Google.Apis.Drive.v3.Data.File();
            fileMetaData.Name    = Path.GetFileName(fileToUpload);
            fileMetaData.Parents = new string[] { parentDriveFolder };

            Console.WriteLine("Uploading to Google Drive: " + fileMetaData.Name);
            FilesResource.CreateMediaUpload createRequest = null;
            FilesResource.UpdateMediaUpload updateRequest = null;
            using (var stream = new FileStream(fileToUpload, FileMode.Open))
            {
                if (fileId != null)
                {
                    updateRequest        = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId, stream, null);
                    updateRequest.Fields = "id";
                    updateRequest.Upload();
                }
                else
                {
                    createRequest        = service.Files.Create(fileMetaData, stream, null);
                    createRequest.Fields = "id";
                    createRequest.Upload();
                }
            }
            fileId = createRequest != null ? fileId = createRequest.ResponseBody.Id : fileId;

            Google.Apis.Drive.v3.Data.Permission readPermission = new Google.Apis.Drive.v3.Data.Permission();
            readPermission.Role = "reader";
            readPermission.Type = "anyone";
            service.Permissions.Create(readPermission, fileId).Execute();

            string shareableUrl = "https://drive.google.com/uc?export=download&id=" + fileId;

            Console.WriteLine("Successfully uploaded " + fileMetaData.Name + ": " + shareableUrl);

            return(shareableUrl);
        }
        /// <summary>
        /// Updates an existing file's metadata and content.
        /// </summary>
        /// <param name="fileId">ID of the file to update.</param>
        /// <param name="path">Filename of the new content to upload.</param>
        /// <param name="newName">New title for the file.</param>
        /// <param name="newMimeType">New MIME type for the file.</param>
        /// <returns><c>true</c> if uploading was successful, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Maximum uploading file size exceeded.
        /// </exception>
        private bool UpdateFile(string fileId, string path, string newName, string newMimeType)
        {
            // First retrieve the file from the API.
            GoogleDriveData.File file = GoogleDriveService.Files.Get(fileId).Execute();

            // File's new metadata.
            var newContent = new GoogleDriveData.File
            {
                MimeType = newMimeType ?? file.MimeType,
                Name     = newName ?? file.Name
            };

            using (var stream = new FileStream(path, FileMode.Open))
            {
                if (stream.Length > _maxFileLength)
                {
                    var ex = new ArgumentOutOfRangeException(nameof(stream), stream.Length,
                                                             $"File size {stream.Length} is greater than maximum for uploading (10MB)."
                                                             );
                    _logger.Error(ex, "Maximum uploading file size exceeded.");
                    throw ex;
                }

                // Send the request to the API.
                FilesResource.UpdateMediaUpload request = GoogleDriveService.Files.Update(
                    newContent, fileId, stream, newContent.MimeType
                    );

                // Add handlers which will be notified on progress changes and upload completion.
                // Notification of progress changed will be invoked when the upload was started,
                // on each upload chunk, and on success or failure.
                request.ProgressChanged  += Upload_ProgressChanged;
                request.ResponseReceived += Upload_ResponseReceived;

                IUploadProgress result = request.Upload();
                return(result.Status == UploadStatus.Completed);
            }
        }
Пример #30
0
        private void UpdateGoogleDocument()
        {
            try
            {
                // First retrieve the file from the API.
                File file = this.GoogleAPI.Files.Get(this.FileID).Execute();

                // File's new content.
                System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(this.CurrentIP));

                // Send the request to the API.
                FilesResource.UpdateMediaUpload request = this.GoogleAPI.Files.Update(file, this.FileID, stream, file.MimeType);
                request.NewRevision = true;
                request.Upload();

                //File updatedFile = request.ResponseBody;
                //return updatedFile;
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred: " + e.Message, "Update document error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }