Beispiel #1
0
        /// <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);
            }
        }
Beispiel #2
0
            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);
            }
Beispiel #3
0
        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");
            }
        }
 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);
     }
 }
Beispiel #5
0
        private async void uploadFileProcess(string path)
        {
            btnUpload.Enabled = false;
            this.AllowDrop    = false;
            try
            {
                System.IO.FileInfo fI = new System.IO.FileInfo(path);
                uploadfilesize = fI.Length;
                FilesResource.CreateMediaUpload request = gd.uploadFile(service, path, "");
                request.Fields           = "id";
                request.ProgressChanged += Request_ProgressChanged;
                FileItemUpload fileItemUpload = new FileItemUpload();
                fileItemUpload.name.Text = System.IO.Path.GetFileName(path).ToString();
                fileItemUpload.fileIcon.BackgroundImage = misc.getFileIcon(misc.getFileExtention(System.IO.Path.GetFileName(path).ToString()));
                fileItemUpload.size.Text = ByteSize.FromBytes((double)fI.Length).ToString();
                progressBar = fileItemUpload.progress;
                flpMain.Controls.Add(fileItemUpload);
                flpMain.Controls.SetChildIndex(fileItemUpload, 0);
                timer1.Enabled = true;
                timer1.Start();
                await request.UploadAsync();

                gd.filePermission("anyone", request.ResponseBody.Id);
            } catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                btnUpload.Enabled = true;
                this.AllowDrop    = true;
            }
        }
Beispiel #6
0
 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());
     }
 }
Beispiel #7
0
        // 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);
            }
        }
 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);
 }
Beispiel #9
0
        ///

        /// 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);
            }
        }
Beispiel #10
0
        public async Task ResumableChunkUpload(string filePath)
        {
            using (var client = DriveClient.GetInfo())
            {
                try
                {
                    FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    FilesResource.CreateMediaUpload request = new FilesResource.CreateMediaUpload(client,
                                                                                                  new Google.Apis.Drive.v3.Data.File
                    {
                        Name    = "new File",
                        Parents = new List <string>()
                        {
                            "1K46j8qE2sOiFAMNvSz21xFxgpVTYlcWm"
                        },
                    },
                                                                                                  stream,
                                                                                                  "video/mpeg4");
                    request.ChunkSize = 1024 * 1024;
                    await request.InitiateSessionAsync();

                    Task <Google.Apis.Upload.IUploadProgress> uploadTask = request.UploadAsync();
                    for (var i = 0; i < 1000; i++)
                    {
                        System.Threading.Thread.Sleep(1000);
                        Console.WriteLine(request.GetProgress().BytesSent);
                    }
                    await uploadTask;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message + " " + e.StackTrace);
                }
            }
        }
        //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());
        }
Beispiel #12
0
        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}");
        }
Beispiel #13
0
        // 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));
        }
Beispiel #14
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);
            }
        }
        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);
        }
Beispiel #16
0
        public bool UploadCloudFile(FileBlock file, string destinationPath = null)
        {
            bool status = false;

            try
            {
                using (var client = DriveClient.GetInfo())
                {
                    using (var stream = new FileStream(file.path, FileMode.OpenOrCreate))
                    {
                        FilesResource.CreateMediaUpload request = new FilesResource.CreateMediaUpload(client,
                                                                                                      new Google.Apis.Drive.v3.Data.File
                        {
                            Name    = file.Name,
                            Parents = file.Parent,
                        },
                                                                                                      stream,
                                                                                                      file.mimeType);
                        request.ChunkSize = 1024 * 1024;
                        Task initiateSessionTask = Task.Run(() => request.InitiateSessionAsync());
                        initiateSessionTask.Wait();
                        Task <Google.Apis.Upload.IUploadProgress> uploadTask = Task.Run(() => request.UploadAsync());
                        uploadTask.Wait();
                        status = true;
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message + " " + e.StackTrace);
            }

            return(status);
        }
Beispiel #17
0
 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);
     }
 }
Beispiel #18
0
        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.");
            }
        }
 /// <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);
     }
 }
        /// <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);
            }
        }
Beispiel #21
0
 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;
     }
 }
Beispiel #22
0
        /// <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));
        }
 /**
  * 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);
     }
 }
Beispiel #24
0
 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);
         body.Parents     = new List <string> {
             _parent
         };                                         // 폴더에 업로드하려면 UN 주석 (위의 방법에서 상위 폴더의 ID를 매개 변수로 보내야 함)
         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.UploadAsync();
             return(request.ResponseBody);
         }
         catch (Exception e)
         {
             Console.WriteLine("Error: " + e.Message);
             return(null);
         }
     }
     else
     {
         MessageBox.Show("파일이 없습니다.", "404");
         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);
     }
 }
        private async Task <bool> UploadToGoogleDrive(DriveService service, string fileToUpload, string parentId)
        {
            await RemoveExistingFileIfExists(service, fileToUpload, parentId).ConfigureAwait(false);

            await using Stream fileToUploadStream = new FileStream(
                            fileToUpload, FileMode.Open, FileAccess.Read, FileShare.None, 4096, useAsync: true);

            GoogleData.File fileMetadata = new GoogleData.File()
            {
                Name    = fileToUpload,
                Parents = new string[] { parentId }
            };

            FilesResource.CreateMediaUpload createRequest =
                service.Files.Create(fileMetadata, fileToUploadStream, null);
            createRequest.Fields = "id";

            IUploadProgress uploadProgress = await createRequest.UploadAsync().ConfigureAwait(false);

            if (uploadProgress.Status != UploadStatus.Completed)
            {
                mLogger.LogWarning($"Uploaded {fileToUpload} to {mTaskerDriveDirectory}. " +
                                   $"Bytes: {uploadProgress.BytesSent}. Status: {uploadProgress.Status}");
                return(false);
            }

            mLogger.LogDebug($"Uploaded {fileToUpload} to {mTaskerDriveDirectory}. " +
                             $"Bytes: {uploadProgress.BytesSent}. Status: {uploadProgress.Status}");

            return(true);
        }
Beispiel #27
0
        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);
        }
Beispiel #28
0
 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);
     }
 }
Beispiel #29
0
        // 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("");
        }
Beispiel #30
0
        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";
            }
        }