Example #1
0
        /// <summary>
        /// Downloads a file from a drive
        /// </summary>
        /// <param name="fileId">Id of file</param>
        /// <returns>PGDriveResult with a FileDownloadResult which contains memory stream of downloaded file, mimeType
        /// and it's extension
        /// </returns>
        public PGDriveResult <FileDownloadResult> DownloadFile(string fileId)
        {
            PGDriveResult <FileDownloadResult> pGDriveResult = new PGDriveResult <FileDownloadResult>();

            try
            {
                var fileRequest = driveService.Files.Get(fileId);
                fileRequest.Fields = DefaultFileFieldsOnResponse;
                var fileResponse = fileRequest.Execute();
                if (fileResponse.MimeType.Contains("folder"))
                {
                    throw CustomExceptions.isAFolder(fileId, driveService);
                }
                var request = driveService.Files.Get(fileId);
                var stream  = new System.IO.MemoryStream();
                request.Download(stream);
                if (stream.Length != 0)
                {
                    string             mimeType           = fileResponse.MimeType;
                    string             ext                = GetDefaultExtension(mimeType);
                    FileDownloadResult fileDownloadResult = new FileDownloadResult(stream, mimeType, ext);
                    pGDriveResult.SetResponseBody(fileDownloadResult);
                }
                else
                {
                    pGDriveResult.SetResponseBody(null);
                    pGDriveResult.SetIsSuccess(false);
                }
                return(pGDriveResult);
            }
            catch (Google.GoogleApiException exception)
            {
                pGDriveResult.InitializeError(exception);
                return(pGDriveResult);
            }
        }