コード例 #1
0
 public void Download(string fileId, string dst)
 {
     FilesResource.GetRequest request = this.Service.Files.Get(fileId);
     request.MediaDownloader.ProgressChanged += this.GoogleDriveDownloadProgress;
     using var stream = new FileStream(dst, FileMode.Create);
     request.Download(stream);
 }
コード例 #2
0
ファイル: GoogleDriveUtil.cs プロジェクト: sewil/chord
        public static void DownloadFile(FilesResource.GetRequest getRequest, string saveTo)
        {
            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.
            getRequest.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.");
                    SaveStream(stream, saveTo);
                    break;
                }

                case Google.Apis.Download.DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            getRequest.Download(stream);
        }
コード例 #3
0
 public bool ReadFile(String fileName)
 {
     try
     {
         if (SearchFile(fileName))
         {
             MemoryStream stream = new MemoryStream();
             FilesResource.GetRequest getRequest = driveService.Files.Get(driveFile.Id);
             getRequest.Download(stream);
             stream.Position = 0;
             StreamReader reader = new StreamReader(stream);
             fileData = reader.ReadToEnd();
             fileData = removeNewLineCharacters(fileData);
         }
         else
         {
             Debug.WriteLine("Error searching for file");
             return false;
         }
         return true;
     }catch (Exception e)
     {
         Debug.WriteLine("Error ... " + e.Message);
         return false;
     }
 }
コード例 #4
0
        private static string DownloadFile(DriveService service, string fileid)
        {
            string Folderpath = "DriveFiles";

            FilesResource.GetRequest request = service.Files.Get(fileid);
            string       filename            = request.Execute().Name;
            string       filepath            = System.IO.Path.Combine(Folderpath, filename);
            MemoryStream memorystream        = new MemoryStream();

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

                case DownloadStatus.Completed:
                {
                    SaveStream(memorystream, filepath);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    break;
                }
                }
            };
            request.Download(memorystream);
            return(filepath);
        }
コード例 #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        private void DownloadFile(FilesResource.GetRequest request, string path)
        {
            MemoryStream downloadStream = new MemoryStream();

            request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                case DownloadStatus.Downloading:
                {
                    this.logger.Debug($"Downloading games data archive (Downloaded {progress.BytesDownloaded} bytes.");
                    break;
                }

                case DownloadStatus.Completed:
                {
                    this.logger.Debug($"Finished downloading games data archive.");

                    System.IO.File.WriteAllBytes(path, downloadStream.ToArray());

                    // TODO: Add notification.
                    break;
                }

                case DownloadStatus.Failed:
                {
                    this.logger.Error($"Could not download games data archive from Google Drive. Exception: {progress.Exception}");
                    // TODO: Add error notification.
                    break;
                }
                }
            };

            request.Download(downloadStream);
        }
コード例 #6
0
        public static MemoryStream GetAudioFile(string id)
        {
            FilesResource.GetRequest getRequest = Instance._service.Files.Get(id);
            var stream = new MemoryStream();

            getRequest.Download(stream);
            return(stream);
        }
コード例 #7
0
ファイル: GDrive.cs プロジェクト: wolatile/A_levelCoursework
        public void DownloadDatabase()
        {
            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields   = "nextPageToken, files(id, name)";

            // List files.

            IList <Google.Apis.Drive.v3.Data.File> files = (IList <Google.Apis.Drive.v3.Data.File>)GetDriveFiles();

            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    if (file.Name.IndexOf(".db") != -1)
                    {
                        DirectoryInfo directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                        FileInfo[]    fileInfo  = directory.GetFiles(file.Name);

                        if (fileInfo.Length != 0)
                        {
                            foreach (var delete in fileInfo)
                            {
                                delete.Delete();
                            }
                        }

                        FilesResource.GetRequest request = service.Files.Get(file.Id);
                        MemoryStream             stream  = new System.IO.MemoryStream();

                        request.Download(stream);

                        request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
                        {
                            if (progress.Status == DownloadStatus.Completed)
                            {
                                new MessageForm("successful").Show();
                            }
                            else if (progress.Status == DownloadStatus.Failed)
                            {
                                MessageForm errorForm = new MessageForm("Failed to download database");
                                errorForm.Show();
                            }
                        };


                        using (System.IO.FileStream download = new FileStream(AppDomain.CurrentDomain.BaseDirectory + @"\database.db", FileMode.Create, FileAccess.Write))
                        {
                            download.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
                        }

                        stream.Flush();
                        stream.Close();
                    }
                }
            }
        }
コード例 #8
0
        public String GetFile(String googleDriveFileID)
        {
            FilesResource.GetRequest request = this.DriveService.Files.Get(googleDriveFileID);
            string name = Path.GetTempFileName();

            using (FileStream stream = new System.IO.FileStream(name, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                request.Download(stream);
            }
            return(name);
        }
コード例 #9
0
        /// <summary>
        /// Downloads file from Google Drive.
        /// </summary>
        /// <param name="fileId">File ID to download. You can get it from Google Drive API.</param>
        /// <param name="saveTo">Filename to save on local storage.</param>
        private void DownloadFile(string fileId, string saveTo)
        {
            using var stream = new MemoryStream();

            FilesResource.GetRequest request = GoogleDriveService.Files.Get(fileId);

            // 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 +=
                progress => ProgressChanged_Callback(progress, stream, saveTo, string.Empty);
            request.Download(stream);
        }
コード例 #10
0
 /// <summary>
 /// Скачивает файл
 /// </summary>
 /// <param name="localFilePath">Куда</param>
 /// <returns></returns>
 public bool DownloadFile(string localFilePath)
 {
     if (Service == null)
     {
         return(false);
     }
     FilesResource.GetRequest getRequest = Service.Files.Get(fileId);
     getRequest.Execute();
     using (FileStream fsDownload = new FileStream(localFilePath, FileMode.Create))
     {
         getRequest.Download(fsDownload);
     }
     return(true);
 }
コード例 #11
0
ファイル: DriveApi.cs プロジェクト: SirEleot/GenesisLauncher
        private void DownloadFile(Google.Apis.Drive.v3.Data.File file, string path, bool needKey = true)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                FilesResource.GetRequest request = _service.Files.Get(file.Id);
                request.MediaDownloader.ProgressChanged += (Action <IDownloadProgress>)(p =>
                {
                    switch (p.Status)
                    {
                    case DownloadStatus.NotStarted:
                        Logger.LogIt($"Ошибка загрузки файла {file.Name}  #1");
                        break;

                    case DownloadStatus.Downloading:
                        break;

                    case DownloadStatus.Completed:
                        SaveStream(ms, path, file.ModifiedTime.Value);
                        break;

                    case DownloadStatus.Failed:
                        Logger.LogIt($"Ошибка загрузки файла {file.Name}  #2");
                        break;

                    default:
                        break;
                    }
                });
                request.Download((Stream)ms);
            }
            if (needKey)
            {
                Google.Apis.Drive.v3.Data.File key = _remoteKeyList.FirstOrDefault(f => f.Name == file.Name + "." + _config.KeyName + ".bisign");
                if (key != null)
                {
                    string FullKeyName = _config.ModPath + @"\" + file.Name + "." + _config.KeyName + ".bisign";
                    if (System.IO.File.Exists(FullKeyName))
                    {
                        System.IO.File.Delete(FullKeyName);
                    }
                    DownloadFile(key, FullKeyName, false);
                }
                else
                {
                    Logger.LogIt($"Ключ {file.Name + "." + _config.KeyName + ".bisign"}  для файла {file.Name} не обнаружен");
                }
            }
        }
コード例 #12
0
        //Download file từ Google Drive
        public static string DownloadGoogleFile(string fileId)
        {
            DriveService service = GetService();

            string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");

            FilesResource.GetRequest request = service.Files.Get(fileId);

            string FileName = request.Execute().Name;
            string FilePath = System.IO.Path.Combine(FolderPath, FileName);

            MemoryStream stream1 = new MemoryStream();

            request.Download(stream1);
            return(FilePath);
        }
コード例 #13
0
        //Download file from Google Drive by fileID.
        public static string DownloadGoogleFile(string fileId)
        {
            DriveService service = GetService();

            // TODO FolderPath2 modified path downloaded File into MyDocuments
            string FolderPath2 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string FolderPath3 = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string FolderPath  = Path.GetExtension("/GoogleDriveFiles/");

            FilesResource.GetRequest request = service.Files.Get(fileId);

            string FileName = request.Execute().Name;
            string FilePath = Path.Combine(FolderPath2, FileName);

            MemoryStream stream1 = new 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 DownloadStatus.Downloading:
                {
                    Console.WriteLine(progress.BytesDownloaded);
                    break;
                }

                case DownloadStatus.Completed:
                {
                    Console.WriteLine("Download complete.");
                    SaveStream(stream1, FilePath);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream1);
            return(FilePath);
        }
コード例 #14
0
        //Download file from Google Drive by fileId.
        public static string DownloadGoogleFile(string fileId)
        {
            DriveService service = GetService();

            string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");

            FilesResource.GetRequest request = service.Files.Get(fileId);

            string FileName = request.Execute().Name;
            string FilePath = System.IO.Path.Combine(FolderPath, FileName);

            MemoryStream stream1 = new 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 DownloadStatus.Downloading:
                {
                    Console.WriteLine(progress.BytesDownloaded);
                    break;
                }

                case DownloadStatus.Completed:
                {
                    Console.WriteLine("Download complete.");
                    SaveStream(stream1, FilePath);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream1);
            return(FilePath);
        }
コード例 #15
0
        public static string DownloadGoogleFile(string fileId)
        {
            DriveService service = GetService();

            string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");

            FilesResource.GetRequest request = service.Files.Get(fileId);

            var receivedFile = request.Execute();

            string FileName = request.Execute().Name;
            string FilePath = System.IO.Path.Combine(FolderPath, FileName);

            MemoryStream stream1 = new MemoryStream();

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

                case DownloadStatus.Completed:
                {
                    //Console.WriteLine("Download complete.");
                    SaveStream(stream1, FilePath);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    //Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream1);
            return(FilePath);
        }
コード例 #16
0
        /// <summary>
        /// Download a file and return a string with its content.
        /// </summary>
        /// <param name="service">The Google Drive service</param>
        /// <param name="file">The Google Drive File instance</param>
        /// <param name="filePath">The local file name and path to download to (timestamp will be appended)</param>
        /// <returns>File's path if successful, null or empty otherwise.</returns>
        private string downloadFile(DriveService service, File file, string filePath)
        {
            if (file == null || String.IsNullOrEmpty(file.Id) || String.IsNullOrEmpty(filePath))
            {
                return(null);
            }

            string downloadFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filePath),
                                                             System.IO.Path.GetFileNameWithoutExtension(filePath))
                                      + DateTime.Now.ToString("_yyyyMMddHHmmss")
                                      + System.IO.Path.GetExtension(filePath);

            FilesResource.GetRequest request = service.Files.Get(file.Id);
            using (System.IO.FileStream fileStream = new System.IO.FileStream(downloadFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                request.Download(fileStream);
            }

            return(downloadFilePath);
        }
コード例 #17
0
        private void DownloadDatabase()
        {
            var memoryStream = new MemoryStream();

            FilesResource.GetRequest getRequest = driveService.Files.Get(databaseId);
            GoogleFile file = getRequest.Execute();

            if (file == null)
            {
                databaseId = null;
                Console.WriteLine("No file found.");
            }
            else
            {
                databaseFile = file;

                getRequest.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => DownloadProgress(progress);
                getRequest.Download(memoryStream);
            }
        }
コード例 #18
0
        public int DownloadGoogleFile(string fileID, string fileSavePath, string name_token)
        {
            int result = -1;

            FilesResource.GetRequest getRequest = Get_Google_Drive_Service(name_token).Files.Get(fileID);
            string FileName = getRequest.Execute().Name;
            string FilePath = System.IO.Path.Combine(fileSavePath, FileName);

            MemoryStream memoryStream = new MemoryStream();

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

                case DownloadStatus.Completed:
                {
                    using (System.IO.FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        memoryStream.WriteTo(file);
                    }

                    result = 1;
                    break;
                }

                case DownloadStatus.Failed:
                {
                    result = 0;
                    break;
                }
                }
            };

            getRequest.Download(memoryStream);
            return(result);
        }
コード例 #19
0
        private void DirectDownloadFile(DfareportingService service, long reportId,
                                        long fileId)
        {
            // Retrieve the file metadata.
            File file = service.Files.Get(reportId, fileId).Execute();

            if ("REPORT_AVAILABLE".Equals(file.Status))
            {
                // Create a get request.
                FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId);

                // Optional: adjust the chunk size used when downloading the file.
                // getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize;

                // Execute the get request and download the file.
                using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file),
                                                                               System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
                    getRequest.Download(outFile);
                    Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name);
                }
            }
        }
コード例 #20
0
        public static bool DownloadFiles(string fileName)
        {
            if (!FileExists(fileName))
            {
                return(false);
            }

            string fileId = GetFileId(fileName);

            FilesResource.GetRequest request = Service.Files.Get(fileId);
            MemoryStream             stream  = new MemoryStream();

            request.MediaDownloader.ProgressChanged += DownloadSucceeded;

            request.Download(stream);
            FileStream file = new FileStream(Savefilepath + fileName, FileMode.Create);

            stream.WriteTo(file);
            file.Close();
            stream.Close();
            return(_downloadSucceeded);
        }
コード例 #21
0
        /// <summary>
        /// Downloads file(from URL) using the Google Drive API
        /// </summary>
        private void DownloadGoogleDriveFile(string url, string fileName, string fileHash)
        {
            string driveId = url.Split(':')[1];

            using (DriveService service = new DriveService(new BaseClientService.Initializer()
            {
                ApiKey = GoogleApiInformation.ApiKey,
                ApplicationName = GoogleApiInformation.ApplicationName
            }))
            {
                FilesResource.GetRequest request = service.Files.Get(driveId);

                using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
                {
                    request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                            OnDownloadProgressChanged(this, new DownloadStatusChangedEventArgs(progress.BytesDownloaded));
                            fileStream.Flush();
                            break;

                        case DownloadStatus.Failed:
                            Exception = progress.Exception;
                            Failed    = true;
                            return;

                        case DownloadStatus.Completed:
                            fileStream.Close();
                            Failed = !VerifyHash(fileName, fileHash);
                            break;
                        }
                    };

                    request.Download(fileStream);
                }
            }
        }
コード例 #22
0
        // File Download Method
        public static string DownloadGoogleFile(string fileId, string path)
        {
            DriveService service = GetService(path);

            string folderPath = @"D:\DriveFiles";

            FilesResource.GetRequest request = service.Files.Get(fileId);

            string fileName = request.Execute().Name;
            string filePath = Path.Combine(folderPath, fileName);

            MemoryStream stream = new MemoryStream();

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

                case DownloadStatus.Completed:
                {
                    SaveStream(stream, filePath);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    break;
                }
                }
            };
            request.Download(stream);

            return(filePath);
        }
コード例 #23
0
        public void DownloadFile(string fileId, string path)
        {
            //TODO: refactor
            var stream = new FileStream(path, FileMode.Create);

            FilesResource.GetRequest request = _driveService.Files.Get(fileId);

            // 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 +=
                progress =>
            {
                switch (progress.Status)
                {
                case DownloadStatus.Completed:
                {
                    Console.WriteLine("Download completed.");

                    stream.Flush();
                    stream.Close();
                    stream.Dispose();

                    OnDownloadCompleted(this, null);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };

            request.Download(stream);
        }
コード例 #24
0
        public void DownloadFile(string fileId)
        {
            DriveService service = GetService();

            FilesResource.GetRequest request = service.Files.Get(fileId);
            string fileName    = request.Execute().Name;
            string newFileName = RemoveCodeInFileName(fileName);
            string FilePath    = Path.Combine(KnownFolders.Downloads.Path, newFileName);
            var    stream      = new MemoryStream();

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

                case DownloadStatus.Completed:
                {
                    //Console.WriteLine("Download complete.");
                    SaveStream(stream, FilePath);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    //Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream);
        }
コード例 #25
0
        public static string DownloadGoogleFile(string fileId)
        {
            DriveService service = GetService();

            string FolderPath = HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");

            FilesResource.GetRequest request = service.Files.Get(fileId);

            string FileName = request.Execute().Name;
            string FilePath = Path.Combine(FolderPath, FileName);

            MemoryStream stream1 = new MemoryStream();

            request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                case DownloadStatus.Downloading:
                {
                    break;
                }

                case DownloadStatus.Completed:
                {
                    SaveStream(stream1, FilePath);
                    break;
                }

                case DownloadStatus.Failed:
                {
                    break;
                }
                }
            };
            request.Download(stream1);
            return(FilePath);
        }
コード例 #26
0
        private void downloadFile(DriveService service, Google.Apis.Drive.v3.Data.File driveFile, string serverDirectory)
        {
            // Make sure all directories exist before downloading
            Directory.CreateDirectory(Path.GetDirectoryName(serverDirectory + driveFile.Name));

            FilesResource.GetRequest getRequest = service.Files.Get(driveFile.Id);
            //getRequest.AcknowledgeAbuse = true;
            MemoryStream stream = new MemoryStream();

            UpdateSubStatusLabel("Downloading: " + driveFile.Name);
            SetSubProgressBarMaximum((int)driveFile.Size);
            UpdateSubProgressBar(0);
            getRequest.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                case Google.Apis.Download.DownloadStatus.Downloading:
                    UpdateSubProgressBar((int)progress.BytesDownloaded);
                    break;

                case Google.Apis.Download.DownloadStatus.Completed:
                    UpdateSubProgressBar(subProgressBar.Maximum);
                    UpdateSubStatusLabel("Downloaded: " + driveFile.Name);
                    SaveStream(stream, serverDirectory + driveFile.Name);
                    Thread.Sleep(25);
                    break;

                case Google.Apis.Download.DownloadStatus.Failed:
                    Console.WriteLine("Download failed.");
                    Console.WriteLine(progress.Exception.Message);
                    break;
                }
            };

            getRequest.Download(stream);
        }
コード例 #27
0
        public void DownloadStyle(string id, string name)
        {
            Task.Run(delegate
            {
                FilesResource.GetRequest request = Service.Files.Get(id);

                var stream = new MemoryStream();

                request.MediaDownloader.ProgressChanged += (IDownloadProgress obj) =>
                {
                    if (obj.Status == DownloadStatus.Completed)
                    {
                        if (DownloadComplete != null)
                        {
                            DownloadComplete(null, new DownloadEventArgs {
                                Stream = stream, Name = name
                            });
                        }
                    }
                };

                request.Download(stream);
            });
        }
コード例 #28
0
ファイル: GoogleDrive.cs プロジェクト: softsingh/GoogleApi
        public static string DownloadFile(string FileID, string DestFolder)
        {
            if (!string.IsNullOrWhiteSpace(DestFolder) && Directory.Exists(DestFolder))
            {
                var file = GetItem(FileID);

                if (file == null)
                {
                    throw new Exception($"Invalid File ID/Path '{FileID}'");
                }

                if (file.MimeType == "application/vnd.google-apps.folder")
                {
                    throw new Exception($"Source '{FileID}' is a Folder");
                }

                bool   failed   = false;
                string FileName = file.Name;
                string FilePath = Path.Combine(DestFolder, FileName);

                FilesResource.GetRequest request   = _service.Files.Get(file.Id);
                MemoryStream             MemStream = new MemoryStream();

                request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                    case DownloadStatus.Downloading:

                        //Console.WriteLine(progress.BytesDownloaded);
                        break;

                    case DownloadStatus.Completed:

                        //Console.WriteLine("Download complete.");
                        SaveMemoryStream(MemStream, FilePath);
                        break;

                    case DownloadStatus.Failed:

                        //Console.WriteLine("Download failed.");
                        failed = true;
                        break;
                    }
                };

                try
                {
                    request.Download(MemStream);

                    if (failed == true)
                    {
                        return(null);
                    }
                    else
                    {
                        return(FilePath);
                    }
                }
                catch (Exception Ex)
                {
                    throw Ex;
                }
            }
            else
            {
                throw new Exception($"Invalid Destination Folder '{DestFolder}'");
            }
        }
コード例 #29
0
        public byte[] Read(long offset, uint bytesRead)
        {
            if (bytesRead == 0)
            {
                return(new byte[0]);
            }

            if (bytesRead == 5)
            {
                int n = 9;
            }

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Id = _fileId
            };

            byte[] readData = null;
            if (ReadFromBuffer(offset, bytesRead, out readData))
            {
                // Adjust offset variable.
                _offset = offset + readData?.Length ?? 0;
                return(readData);
            }

            using (var stream = new MemoryStream())
            {
#if DEBUG
                var sw = new Stopwatch();
                sw.Start();
#endif

                long bytesDownloaded             = 0;
                bool downloadFailed              = false;
                FilesResource.GetRequest request = _service.Files.Get(_fileId);
                request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                    case DownloadStatus.Downloading:
                    {
                        bytesDownloaded += progress.BytesDownloaded;
                        break;
                    }

                    case DownloadStatus.Completed:
                    {
                        break;
                    }

                    case DownloadStatus.Failed:
                    {
                        downloadFailed = true;
                        break;
                    }
                    }
                };


                // Download entire file.
                if (offset == 0 && bytesRead == UInt32.MaxValue)
                {
                    request.Download(stream);
                }
                else
                {
                    request.DownloadRange(stream, new RangeHeaderValue(offset, offset + Math.Max(bytesRead, ReadBufferLength) - 1));
                }

                if (downloadFailed)
                {
                    throw new InvalidOperationException($"File(fileId = '{_fileId}') download has failed!");
                }
#if DEBUG
                sw.Stop();
                Console.WriteLine($"{_offset}: File size download: {stream.Length} Duration: {sw.ElapsedMilliseconds}ms");
#endif
                if (stream.Length > 0)
                {
                    // Keep read bytes in buffer.
                    if (bytesRead < ReadBufferLength)
                    {
                        UpdateReadBuffer(stream);
                        ReadFromBuffer(offset, bytesRead, out readData);
                    }
                    else
                    {
                        stream.Position = 0;
                        readData        = stream.ToArray();
                        ClearReadBuffer();
                    }

                    // Adjust offset variable.
                    _offset = offset + readData?.Length ?? 0;
                }
            }

            return(readData);
        }