コード例 #1
0
ファイル: GoogleDriverConsole.cs プロジェクト: huyqta/MySite
        private void UploadImage(string path, DriveService service, string folderUpload)
        {
            var fileMetadata = new Google.Apis.Drive.v3.Data.File();

            fileMetadata.Name     = Path.GetFileName(path);
            fileMetadata.MimeType = "image/*";

            fileMetadata.Parents = new List <string>
            {
                folderUpload
            };


            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
            {
                request        = service.Files.Create(fileMetadata, stream, "image/*");
                request.Fields = "id";
                request.Upload();
            }

            var file = request.ResponseBody;

            //textBox1.Text += ("File ID: " + file.Id);
        }
コード例 #2
0
ファイル: GoogleApi.cs プロジェクト: JIOO-phoeNIX/DriveApi
        /// <summary>
        /// This method trys to upload the file to Google Drive using the Drive API Service
        /// </summary>
        /// <param name="file">The file to be uploaded</param>
        public static FilesResource.CreateMediaUpload UploadFile(string file)
        {
            DriveService service = CreateService();

            var fileData = new Google.Apis.Drive.v3.Data.File
            {
                Name     = file,
                MimeType = MimeMapping.GetMimeMapping(file)
            };

            //Create a media upload that is used to upload the file to Google Drive
            FilesResource.CreateMediaUpload mediaUpload;

            //Open the file to be uploaded to Google Drive
            using (FileStream stream = new FileStream(file, FileMode.Open))
            {
                //Create the file
                mediaUpload        = service.Files.Create(fileData, stream, fileData.MimeType);
                mediaUpload.Fields = "id";

                //Upload the file to Google Drive
                mediaUpload.UploadAsync();
            }

            return(mediaUpload);
        }
コード例 #3
0
        private static void DownloadFile(Google.Apis.Drive.v3.DriveService service, Google.Apis.Drive.v3.Data.File file, string saveTo)
        {
            var request = service.Files.Get(file.Id);
            var stream  = new System.IO.MemoryStream();

            request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                case Google.Apis.Download.DownloadStatus.Downloading:
                {
                    Console.WriteLine(progress.BytesDownloaded);
                    break;
                }

                case Google.Apis.Download.DownloadStatus.Completed:
                {
                    Console.WriteLine("Download complete.");
                    SaveStreamto(stream, saveTo);
                    break;
                }

                case Google.Apis.Download.DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream);
        }
コード例 #4
0
        //file Upload to the Google Drive.
        public static string FileUpload(string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
        {
            DriveService _service = GetService();

            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
                };


                FilesResource.CreateMediaUpload request;

                using (var stream = new System.IO.FileStream(_uploadFile, System.IO.FileMode.Open))
                {
                    request        = _service.Files.Create(body, stream, GetMimeType(_uploadFile));
                    request.Fields = "id, name, webViewLink";
                    request.Upload();

                    return(request.ResponseBody.WebViewLink);
                }
            }
            else
            {
                return(null);
            }
        }
コード例 #5
0
ファイル: AudioPlayer.cs プロジェクト: TBTBTBT/Bullet
        public void SetNext(File file, string ext)
        {
            if (StringToExtension.ContainsKey(ext))
            {
                currentTrack.Extension = StringToExtension[ext];
            }

            nextTrack.FileCache = file;
            nextTrack.State     = TrackState.Loading;
            new Thread(delegate(object o)
            {
                //var response = WebRequest.Create(url).GetResponse();
                using (var stream = GoogleDriveApiManager.GetAudioFile(file.Id)) //response.GetResponseStream())
                {
                    byte[] buffer   = new byte[65536];                           // 64KB chunks
                    stream.Position = 0;
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        nextTrack.Data.Position = nextTrack.Data.Length;
                        nextTrack.Data.Write(buffer, 0, read);
                    }
                }
                nextTrack.Data.Position = 0;
                nextTrack.State         = TrackState.Playable;
            }).Start();
        }
コード例 #6
0
        private void ProcessFiles(
            FileInfo[] files,
            Google.Apis.Drive.v3.Data.File serverFolder,
            IList <Google.Apis.Drive.v3.Data.File> serverFiles)
        {
            foreach (FileInfo file in files)
            {
                bool retry   = false;
                bool success = false;
                retries = 2;

                while ((success == false) && (retries > 0))
                {
                    success = BackUpFile(
                        serverFolder, serverFiles, file, retry);

                    if ((success == false) && (retries > 0))
                    {
                        retry = true;
                        System.Threading.Thread.Sleep(200);
                    }
                }
            }

            RemoveAbandonedFiles(files, serverFiles);
        }
コード例 #7
0
        public async Task <string> GetFolderID(string email, string folderName)
        {
            var credential = creditinalStorage[email].credential;
            var service    = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            var filemetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name     = folderName,
                MimeType = "application/vnd.google-apps.folder"
            };

            string pageToken = null;
            var    request   = service.Files.List();

            request.Q         = "mimeType='application/vnd.google-apps.folder' and name='" + folderName + "'";
            request.Spaces    = "drive";
            request.Fields    = "nextPageToken, files(id, name)";
            request.PageToken = pageToken;
            var result = request.Execute();

            return(result.Files.FirstOrDefault() != null?result.Files.FirstOrDefault().Id : "");
        }
        private void QRscan(System.IO.MemoryStream stream, Google.Apis.Drive.v3.Data.File file)
        {
            BarcodeReader reader = new BarcodeReader();

            reader.AutoRotate              = true;
            reader.Options.TryHarder       = true;
            reader.Options.PureBarcode     = false;
            reader.Options.PossibleFormats = new List <BarcodeFormat>();
            reader.Options.PossibleFormats.Add(BarcodeFormat.QR_CODE);

            try
            {
                var res    = Image.FromStream(stream);
                var result = reader.Decode((Bitmap)res);
                if (result != null)
                {
                    ibl.AddItem(CreateItem(result.ToString(), file.CreatedTime));
                }
                else
                {
                    Console.WriteLine("failed to scan");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #9
0
        public static bool UploadSimple(string fileName)
        {
            Google.Apis.Drive.v3.DriveService driveService = new DriveService();

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = "myTestPhoto.jpg"
            };

            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(fileName,
                                                         System.IO.FileMode.Open))
            {
                request = driveService.Files.Create(
                    fileMetadata, stream, "image/jpeg");
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;

            Console.WriteLine("File ID: " + file.Id);



            return(false);
        }
コード例 #10
0
        private static async void UploadFileToDrive(DriveService service, string contentType, TelegramBotClient botClient, string fileId, string folderId)
        {
            var fileMetadata = new File
            {
                Name    = fileId,
                Parents = new List <string> {
                    folderId
                }
            };

            FilesResource.CreateMediaUpload request;


            var photo = await botClient.GetFileAsync(fileId);


            MemoryStream ms;

            using (ms = new MemoryStream())
            {
                await botClient.DownloadFileAsync(photo.FilePath, ms);
            }

            using (var stream = ms)
            {
                request = service.Files.Create(fileMetadata, stream, contentType);
                request.Upload();
            }
            var file = request.ResponseBody;
        }
        // Download file from Google drive
        private void DownloadFile(Google.Apis.Drive.v3.DriveService service, Google.Apis.Drive.v3.Data.File file)//, string saveTo)
        {
            var request = service.Files.Get(file.Id);
            var stream  = new System.IO.MemoryStream();

            // Add a handler which will be notified on progress changes.
            // It will notify on each chunk download and when the
            // download is completed or failed.
            request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                case Google.Apis.Download.DownloadStatus.Downloading:
                {
                    Console.WriteLine(progress.BytesDownloaded);
                    break;
                }

                case Google.Apis.Download.DownloadStatus.Completed:
                {
                    Console.WriteLine("Download complete.");
                    QRscan(stream, file);
                    break;
                }

                case Google.Apis.Download.DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream);
        }
コード例 #12
0
    //file Upload to the Google Drive root folder.
    public static string UploadToDrive(DriveService driveService, HttpPostedFileBase file)
    {
        if (file != null && file.ContentLength > 0)
        {
            //upload to server
            string path = Path.Combine(_GoogleDrivePhysicalPath, Path.GetFileName(file.FileName));
            file.SaveAs(path);

            var FileMetaData = new Google.Apis.Drive.v3.Data.File();
            FileMetaData.Name     = Path.GetFileName(file.FileName);
            FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);
            FileMetaData.Parents  = new List <string> {
                _GoogleSharedFolderId
            };

            //upload to drive
            FilesResource.CreateMediaUpload request;
            using (var stream = new FileStream(path, FileMode.Open))
            {
                request        = driveService.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                request.Fields = "id";
                request.Upload();
            }

            //delete file on server
            File.Delete(path);

            return(request.ResponseBody.Id);
        }

        return(null);
    }
コード例 #13
0
ファイル: GoogleDrive.cs プロジェクト: wagnerteixeira/systore
        public bool UploadZipedFile(string zipedFile)
        {
            var service      = GetDriveService();
            var name         = Path.GetFileName(zipedFile);
            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name    = name,
                Parents = new List <string> {
                    _backupConfigurations.ParentFolderInDrive
                }
            };

            FilesResource.CreateMediaUpload request;

            using (var stream = new System.IO.FileStream(zipedFile,
                                                         System.IO.FileMode.Open))
            {
                request = service.Files.Create(
                    fileMetadata, stream, "application/zip");

                request.Fields = "id";
                //   request.ProgressChanged += Request_ProgressChanged;
                //   request.ResponseReceived += Request_ResponseReceived;
                request.Upload();
                _logger.LogInformation($"File {name} uploaded to google drive");
            }

            var file = request.ResponseBody;

            return(!string.IsNullOrWhiteSpace(file?.Id));
        }
コード例 #14
0
        /// <summary>
        /// If folder with param name exists, return FolderId of exists folder.
        /// Or create new folder
        /// </summary>
        /// <param name="folderName">Folder name</param>
        /// <returns>Folder.Id</returns>
        public string CreateOrGetFolder(string folderName)
        {
            var existingFolders = GetFolders();

            foreach (var folder in existingFolders)
            {
                if (folder.Name == folderName)
                {
                    return(folder.Id);
                }
            }

            var body = new File
            {
                Name     = folderName,
                MimeType = FolderMimeType
            };

            var createdFolder = service
                                .Files
                                .Create(body)
                                .Execute();

            return(createdFolder.Id);
        }
コード例 #15
0
 private void Request_ResponseReceived(Google.Apis.Drive.v3.Data.File obj)
 {
     if (obj != null)
     {
         MessageBox.Show("File was uploaded sucessfully--");
     }
 }
コード例 #16
0
ファイル: Program.cs プロジェクト: lesiak/google-api-samples
        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}");
        }
コード例 #17
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);
         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.", "404");
         return(null);
     }
 }
コード例 #18
0
 public GoogleDriveManagerResult GetFile(DriveService service, string fileId)
 {
     result = new GoogleDriveManagerResult();
     try
     {
         FilesResource.GetRequest       request = service.Files.Get(fileId);
         Google.Apis.Drive.v3.Data.File file    = request.Execute();
         if (file != null)
         {
             GoogleDriveFile gdf = new GoogleDriveFile()
             {
                 Id          = file.Id,
                 Name        = file.Name,
                 Size        = file.Size,
                 Version     = file.Version,
                 CreatedTime = file.CreatedTime
             };
             result.GoogleDriveFile = gdf;
         }
         else
         {
             WriteToConsole(GoogleDriveManagementConstants.FileNotFound + fileId);
             result.Errors.Add(GoogleDriveManagementConstants.FileNotFound);
         }
         return(result);
     }
     catch (Exception e)
     {
         result.Exceptions.Add(e);
         WriteToConsole(GoogleDriveManagementConstants.GettingFileException + fileId);
         return(result);
     }
 }
コード例 #19
0
        public async void Upload(string email, string audioName, string folderId)
        {
            var credential = creditinalStorage[email].credential;
            var service    = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

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

            fileMetadata.Name        = audioName;
            fileMetadata.Description = audioName;
            fileMetadata.Parents     = new List <string> {
                folderId
            };
            fileMetadata.MimeType = GetMimeType(getPathToFile(audioName));
            Console.WriteLine(fileMetadata.MimeType + "metadata");
            //FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(getPathToFile(audioName), System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                var request = service.Files.Create(
                    fileMetadata, stream, fileMetadata.MimeType);
                request.Fields = "id";
                var error = request.Upload();
                Console.WriteLine(error + "error");
                var fileres = request.ResponseBody;
                Console.WriteLine("uploaded");
                Console.WriteLine("file loaded:" + fileres.Id);
            }
        }
コード例 #20
0
 /// <summary>
 /// Create a new Directory file on Google Drive: GoogleDriveService.Files.Create(metaData)
 /// </summary>
 /// a Valid authenticated DriveService
 /// The title of the file. Used to identify file or folder name.
 /// A short description of the file.
 /// Collection of parent folders which contain this file.
 /// Setting this field will put the file in all of the provided folders. root folder.
 /// Documentation: https://developers.google.com/drive/v3/reference/files/create
 public GoogleDriveManagerResult CreateFolder(DriveService service, string dirName, string description, string parent)
 {
     result = new GoogleDriveManagerResult();
     try
     {
         Google.Apis.Drive.v3.Data.File folder   = null;
         Google.Apis.Drive.v3.Data.File metaData = new Google.Apis.Drive.v3.Data.File()
         {
             Name        = dirName,
             Description = description,
             MimeType    = GoogleDriveMimeService.FolderMimeType
         };
         FilesResource.CreateRequest request = service.Files.Create(metaData);
         folder = request.Execute();
         if (folder != null)
         {
             result.GoogleDriveFileId = folder.Id;
         }
         else
         {
             result.Errors.Add(GoogleDriveManagementConstants.FolderNotCreated);
         }
         return(result);
     }
     catch (Exception e)
     {
         WriteToConsole(GoogleDriveManagementConstants.FolderNotCreatedException + e.Message);
         result.Exceptions.Add(e);
         return(result);
     }
 }
コード例 #21
0
        //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());
        }
コード例 #22
0
 /// <summary>
 /// Untrash a file on Google Drive: GooglDriveService.Files.Updaate
 /// Instead of permanently deleting a file you can simply trash it.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="fileId"></param>
 /// <returns></returns>
 public GoogleDriveManagerResult UnTrashFile(DriveService service, string fileId)
 {
     result = new GoogleDriveManagerResult();
     try
     {
         Google.Apis.Drive.v3.Data.File response = null;
         Google.Apis.Drive.v3.Data.File file     = new Google.Apis.Drive.v3.Data.File();
         if ((bool)file.OwnedByMe)
         {
             file.Trashed = false;
             FilesResource.UpdateRequest request = service.Files.Update(file, fileId);
             response = request.Execute();
             if (response != null)
             {
                 result.GoogleDriveFileId = response.Id;
             }
             else
             {
                 result.Errors.Add(GoogleDriveManagementConstants.UnTrashingFileError);
             }
         }
         else
         {
             result.Errors.Add(GoogleDriveManagementConstants.FileNotOwnedByUserError);
         }
         return(result);
     }
     catch (Exception e)
     {
         WriteToConsole(GoogleDriveManagementConstants.UnTrashingFileException + e.Message);
         result.Exceptions.Add(e);
         return(result);
     }
 }
コード例 #23
0
        public static void Insert(CurrentSettings settings, Google.Apis.Drive.v3.Data.File file, string identifier)
        {
            try
            {
                string connStr = ConnectionString.MySQL(settings.MySQL_output_server, settings.MySQL_input_username, settings.MySQL_output_password, settings.MySQL_output_database);

                if (identifier == null)
                {
                    identifier = string.Empty;
                }

                MySqlParameterList parms = new MySqlParameterList();
                parms.Add(new MySqlParameter("@fileId", file.Id));
                parms.Add(new MySqlParameter("@name", file.Name));
                parms.Add(new MySqlParameter("@size", file.Size));
                parms.Add(new MySqlParameter("@mimeType", file.MimeType));
                parms.Add(new MySqlParameter("@webViewLink", file.WebViewLink));
                parms.Add(new MySqlParameter("@identifier", identifier));
                ExecCmdNonQuery(connStr, "INSERT INTO cgoogledrive (fileId ,name ,size ,mimeType ,webViewLink ,identifer) VALUES (@fileId ,@name ,@size ,@mimeType ,@webViewLink ,@identifier)", CommandType.Text, parms);
            }
            catch (Exception ex)
            {
                ex.Write();
            }
        }
コード例 #24
0
        // Stolen from: https://stackoverflow.com/a/38750409/1621156
        private string AbsPath(Google.Apis.Drive.v3.Data.File file)
        {
            var name = file.Name;

            if (file.Parents.Count() == 0)
            {
                return(name);
            }

            var path = new List <string>();

            while (true)
            {
                var parent = GetFile(file.Parents[0]);

                // Stop when we find the root dir
                if (parent.Parents == null || parent.Parents.Count() == 0)
                {
                    break;
                }

                path.Insert(0, parent.Name);
                file = parent;
            }
            path.Add(name);
            return(path.Aggregate((current, next) => Path.Combine(current, next)));
        }
コード例 #25
0
        public byte[] Download(GDriveCredentials cred, string fileId)
        {
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = cred.Credential,
                ApplicationName       = "GMT",
            });

            var  l     = service.Files.List();
            var  list  = l.Execute();
            File file1 = null;

            foreach (var f in list.Files)
            {
                if (fileId.Equals(f.Name, System.StringComparison.OrdinalIgnoreCase))
                {
                    file1 = f;
                }
            }

            if (file1 == null)
            {
                return(null);
            }

            //https://developers.google.com/drive/v3/web/manage-downloads
            var request = service.Files.Get(file1.Id);

            using (var s = new MemoryStream())
            {
                request.Download(s);
                return(s.ToArray());
            }
        }
コード例 #26
0
        static private bool CreateGoogleDriveFolder(String name, String parentID)
        {
            try
            {
                var service      = GetService_v3();
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name     = name,
                    MimeType = "application/vnd.google-apps.folder",
                    Parents  = new List <string>
                    {
                        parentID
                    },
                };
                var request = service.Files.Create(fileMetadata);
                request.Fields = "nextPageToken, files(id, name)";
                var file = request.Execute();

                if (file == null)
                {
                    return(false);
                }
                else
                {
                    Console.WriteLine("new Folder ID: " + file.Id);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                return(true);
            }
        }
コード例 #27
0
        //file Upload to the Google Drive.
        public bool FileUpload(HttpPostedFile file)
        {
            try
            {
                if (file != null && file.ContentLength > 0)
                {
                    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();
                    FileMetaData.Name     = Path.GetFileName(file.FileName);
                    FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);

                    FilesResource.CreateMediaUpload request;

                    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(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
コード例 #28
0
        /// <inheritdoc/>
        public async Task <IUnixDirectoryEntry> CreateDirectoryAsync(
            IUnixDirectoryEntry targetDirectory,
            string directoryName,
            CancellationToken cancellationToken)
        {
            var dirEntry = (GoogleDriveDirectoryEntry)targetDirectory;
            var body     = new File
            {
                Name    = directoryName,
                Parents = new List <string>()
                {
                    dirEntry.File.Id,
                },
            }.AsDirectory();

            var request = Service.Files.Create(body);

            request.Fields = FileExtensions.DefaultFileFields;
            var newDir = await request.ExecuteAsync(cancellationToken);

            return(new GoogleDriveDirectoryEntry(
                       this,
                       newDir,
                       FileSystemExtensions.CombinePath(dirEntry.FullName, newDir.Name)));
        }
コード例 #29
0
        public File SaveFile(File file, Stream fileStream)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (fileStream == null)
            {
                throw new ArgumentNullException("fileStream");
            }

            DriveFile newDriveFile = null;

            if (file.ID != null)
            {
                newDriveFile = GoogleDriveProviderInfo.Storage.SaveStream(MakeDriveId(file.ID), fileStream, file.Title);
            }
            else if (file.FolderID != null)
            {
                newDriveFile = GoogleDriveProviderInfo.Storage.InsertEntry(fileStream, file.Title, MakeDriveId(file.FolderID));
            }

            GoogleDriveProviderInfo.CacheReset(newDriveFile);
            var parentDriveId = GetParentDriveId(newDriveFile);

            if (parentDriveId != null)
            {
                GoogleDriveProviderInfo.CacheReset(parentDriveId, false);
            }

            return(ToFile(newDriveFile));
        }
コード例 #30
0
        public async Task <DownloadFileDto> DownloadFile(string fileId)
        {
            DriveService service;

            try
            {
                service = AuthorizationService.ServiceAccountAuthorization();
            }
            catch (Exception e)
            {
                throw e;
            }
            var request = service.Files.Get(fileId);

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

            var stream = new System.IO.MemoryStream();
            await request.DownloadAsync(stream);

            stream.Seek(0, SeekOrigin.Begin);
            DownloadFileDto dto = new DownloadFileDto()
            {
                Name    = file.Name,
                Type    = file.MimeType,
                Content = stream
            };

            return(dto);
        }